阅读量:3
在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中管理文件系统的基本操作。你可以根据需要扩展这些示例以执行更复杂的文件操作。
以上就是关于“Linux使用Python如何管理文件系统”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm