在保存文件之前,可以先检查目标文件是否已经存在。如果存在,可以在文件名后添加一个数字或者时间戳来避免覆盖现有文件。以下是一个示例代码:
import os
import datetime
def save_file(file_path):
if os.path.exists(file_path):
# 文件已存在,生成新的文件名
file_name, file_ext = os.path.splitext(file_path)
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
new_file_path = f"{file_name}_{timestamp}{file_ext}"
print(f"文件已存在,保存为新文件: {new_file_path}")
# 保存新文件
with open(new_file_path, 'w') as f:
f.write("这是一个新文件")
else:
# 文件不存在,直接保存
with open(file_path, 'w') as f:
f.write("这是一个新文件")
print(f"文件保存成功: {file_path}")
# 调用示例
save_file("test.txt")
在上述示例中,我们首先检查文件是否存在,如果存在,则生成一个新的文件名,格式为"原文件名_时间戳.后缀",然后保存新文件。如果文件不存在,则直接保存。这样就可以避免覆盖现有文件,而是保存一个新的文件。