在Python中,你可以使用os
和shutil
库进行文件操作
import os
import shutil
# 创建一个新文件
with open("new_file.txt", "w") as f:
f.write("Hello, World!")
# 删除一个文件
os.remove("new_file.txt")
# 重命名一个文件
shutil.move("old_file.txt", "new_file.txt")
# 读取文件内容
with open("file.txt", "r") as f:
content = f.read()
print(content)
# 写入文件内容
with open("file.txt", "w") as f:
f.write("Hello, World!")
import os
def list_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
print(os.path.join(root, file))
list_files(".")
import shutil
shutil.copy("source_file.txt", "destination_file.txt")
import shutil
shutil.move("source_file.txt", "destination_file.txt")
import os
if os.path.exists("file.txt"):
print("File exists")
else:
print("File does not exist")
import os
import time
file_path = "file.txt"
# 获取文件大小(字节)
file_size = os.path.getsize(file_path)
print(f"File size: {file_size} bytes")
# 获取文件修改时间
last_modified_time = os.path.getmtime(file_path)
print(f"Last modified time: {time.ctime(last_modified_time)}")
这些示例展示了如何使用Python进行基本的文件操作。你可以根据需要调整这些示例以满足你的需求。