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

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

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

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

标签:Python,避免,文件,同名
0
投稿

猜你喜欢

  • Flask模板引擎之Jinja2语法介绍

    2021-11-15 21:08:11
  • Python中创建表格详细过程

    2023-10-08 02:42:51
  • 对python中的乘法dot和对应分量相乘multiply详解

    2021-01-14 15:54:58
  • 利用Python绘制数据的瀑布图的教程

    2023-03-09 02:33:42
  • mysql 5.7.13 winx64安装配置方法图文教程

    2024-01-25 19:43:37
  • 17个vue常用的数组方法总结与实例演示

    2024-06-07 16:06:07
  • Pyecharts可视化图片渲染的方法详解

    2021-02-02 22:39:30
  • python使用append合并两个数组的方法

    2022-08-07 08:25:05
  • MySQL多表查询与7种JOINS的实现举例

    2024-01-12 23:34:32
  • Javascript简单实现可拖动的div

    2013-08-20 11:46:37
  • 12种实现301网页重定向方法的代码实例(含Web编程语言和Web服务器)

    2023-08-22 23:27:30
  • python中尾递归用法实例详解

    2023-10-09 06:46:15
  • PHP基于phpqrcode类库生成二维码过程解析

    2023-11-17 19:06:35
  • 浅谈用户注册表单

    2008-11-13 12:27:00
  • 几款好用的前端开发编辑器推荐安利

    2023-11-21 13:30:00
  • python中for循环的多种使用实例

    2021-12-17 19:08:14
  • 编写一个asp代码执行器

    2007-09-24 16:05:00
  • 前端图片懒加载的原理与3种实现方式举例

    2024-04-17 10:20:02
  • python+os根据文件名自动生成文本

    2022-06-12 00:50:48
  • HTML的form表单和django的form表单

    2021-08-03 07:04:42
  • asp之家 网络编程 m.aspxhome.com