在Python中优雅地处理文件和路径
在Python中,处理文件和路径通常会用到一些内置的模块,如os
, path
, 和shutil
等。以下是一些常用的处理方法:
检查路径是否存在:
import os
file_path = '/path/to/file'
if os.path.exists(file_path):
print(f"Path exists: {file_path}")
else:
print(f"Path does not exist: {file_path}")
获取文件或目录的完整路径:
import os
file_path = '/path/to/file'
absolute_file_path = os.path.abspath(file_path)
print(f"Absolute File Path: {absolute_file_path}")
创建新文件或重命名文件:
import os
# 创建新文件
new_file_path = '/new/path/to/file.txt'
os.makedirs(os.path.dirname(new_file_path)), exist_ok=True)
with open(new_file_path, 'w')) as file:
file.write('Hello, World!')
# 重命名文件
old_file_path = '/path/to/old/file.txt'
new_file_name = 'new_file.txt'
new_file_path = os.path.join(os.path.dirname(old_file_path))), new_file_name)
if os.path.exists(new_file_path)):
os.replace(old_file_path, new_file_path))
print(f"File {old_file_path}} successfully renamed to {new_file_path}")
else:
print("Renaming failed. File not found.")
以上就是Python中处理文件和路径的一些基本方法。根据实际需求,可能会用到更多高级功能。
还没有评论,来说两句吧...