在Linux中,你可以使用Python的内置库os
和shutil
来管理文件系统
import os
directory_name = "new_directory"
# 检查目录是否已存在
if not os.path.exists(directory_name):
os.makedirs(directory_name)
print(f"{directory_name} created.")
else:
print(f"{directory_name} already exists.")
import shutil
directory_name = "new_directory"
# 检查目录是否存在
if os.path.exists(directory_name):
shutil.rmtree(directory_name)
print(f"{directory_name} deleted.")
else:
print(f"{directory_name} does not exist.")
import shutil
source_file = "source_file.txt"
destination_file = "destination_file.txt"
if os.path.exists(source_file):
shutil.copy2(source_file, destination_file)
print(f"{source_file} copied to {destination_file}.")
else:
print(f"{source_file} does not exist.")
import os
source_file = "source_file.txt"
destination_file = "destination_file.txt"
if os.path.exists(source_file):
os.rename(source_file, destination_file)
print(f"{source_file} moved to {destination_file}.")
else:
print(f"{source_file} does not exist.")
with open("file.txt", "r") as file:
content = file.read()
print(content)
file_name = "file.txt"
content = "Hello, World!"
with open(file_name, "w") as file:
file.write(content)
这些示例展示了如何使用Python在Linux中管理文件系统的基本操作。你可以根据需要扩展这些示例以执行更复杂的文件操作。