以下是20个关于文件操作的Python脚本示例:
with open("file.txt", "r") as file:
content = file.read()
print(content)
with open("file.txt", "w") as file:
file.write("Hello, World!")
with open("file.txt", "a") as file:
file.write("Hello, again!")
with open("file.txt", "r") as file:
for line in file:
print(line.strip())
with open("file.txt", "w") as file:
lines = ["Line 1
", "Line 2
", "Line 3
"]
file.writelines(lines)
with open("source.txt", "r") as source_file, open("destination.txt", "w") as destination_file:
destination_file.write(source_file.read())
import shutil
shutil.move("source.txt", "destination.txt")
import os
os.remove("file.txt")
import os
os.rename("old_name.txt", "new_name.txt")
import os
file_size = os.path.getsize("file.txt")
print(f"File size: {file_size} bytes")
import os
import time
last_modified = os.path.getmtime("file.txt")
print(f"Last modified: {time.ctime(last_modified)}")
import os
os.mkdir("directory")
import os
os.rmdir("directory")
import os
directory_content = os.listdir("directory")
print(directory_content)
import os
os.chdir("directory")
import os
current_directory = os.getcwd()
print(current_directory)
import os
if os.path.exists("file.txt"):
print("File exists")
else:
print("File does not exist")
import os
if os.path.isfile("file.txt"):
print("Path is a file")
else:
print("Path is not a file")
import os
if os.path.isdir("directory"):
print("Path is a directory")
else:
print("Path is not a directory")
import os
def traverse_directory_tree(directory):
for root, dirs, files in os.walk(directory):
print(f"Directory: {root}")
for file in files:
print(f"File: {os.path.join(root, file)}")
traverse_directory_tree("directory")