网络编程
位置:首页>> 网络编程>> Python编程>> Python如何避免文件同名产生覆盖

Python如何避免文件同名产生覆盖

作者:Johnthegreat  发布时间:2021-02-05 21:16:34 

标签: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!')

结果如下:

Python如何避免文件同名产生覆盖

来源:https://www.cnblogs.com/johnthegreat/p/12748790.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com