Python中文件同名产生覆盖的解决办法

Python在一些不多的数据下载和生成的时候,我们倾向于直接保存为文件,当我们修改某些参数后再一次运行时,之前运行时生成的文件就被覆盖了。为了解决Python中文件同名产生覆盖的问题,笔者在这里提供几个解决方案。

python

1. 判断文件是否存在;

2. 判断是否带有”0)“这种数字带括号的格式;

3. 文件名添加”(0), (1), (2)….“之类的编号。

以下是代码:

import os
import re

def auto_save_file(path):
directory, file_name = os.path.split(path)
while os.path.isfile(path):
pattern = '(\d+)\)\.'
if re.search(pattern, file_name) is None:
file_name = file_name.replace('.', '(0).')
else:
current_number = int(re.findall(pattern, file_name)[-1])
new_number = current_number + 1
file_name = file_name.replace(f'({current_number}).', f'({new_number}).')
path = os.path.join(directory + os.sep + file_name)
return path

如果使用如下创建文件的代码测试:

path = r'D:\test.txt'
for i in range(10):
with open(auto_save_file(path), 'w') as f:
f.write('This is a test!')

结果如下:

未经允许不得转载:便宜VPS网 » Python中文件同名产生覆盖的解决办法