在Python中修改文件名通常涉及到两个步骤:读取文件的当前路径,然后重命名该文件。以下是一个简单的方法来实现这个功能:
import os
def rename_file(old_path, new_name):
# 获取文件所在的目录
directory = os.path.dirname(old_path)
# 构造新的文件路径
new_path = os.path.join(directory, new_name)
# 重命名文件
os.rename(old_path, new_path)
return new_path
# 使用示例
old_file_path = '/path/to/your/file.txt'
new_file_name = 'new_file_name.txt'
new_file_path = rename_file(old_file_path, new_file_name)
print(f'File has been renamed to: {new_file_path}')
os.rename
之前,可以使用os.path.exists(old_path)
检查文件是否存在。os.path.exists(new_path)
检查目标文件是否已存在,并采取相应措施(如重命名或覆盖)。为了处理上述可能的问题,可以改进代码如下:
import os
def rename_file(old_path, new_name):
if not os.path.exists(old_path):
raise FileNotFoundError(f"The file {old_path} does not exist.")
directory = os.path.dirname(old_path)
new_path = os.path.join(directory, new_name)
if os.path.exists(new_path):
raise FileExistsError(f"The file {new_path} already exists.")
os.rename(old_path, new_path)
return new_path
# 使用示例
try:
old_file_path = '/path/to/your/file.txt'
new_file_name = 'new_file_name.txt'
new_file_path = rename_file(old_file_path, new_file_name)
print(f'File has been renamed to: {new_file_path}')
except (FileNotFoundError, FileExistsError) as e:
print(e)
通过这种方式,可以更安全地重命名文件,并且处理了可能出现的错误情况。
领取专属 10元无门槛券
手把手带您无忧上云