Python - 实现文件名自动更改,避免同名文件被覆盖的两个解决方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python - 实现文件名自动更改,避免同名文件被覆盖的两个解决方法

Johnthegreat   2020-04-22 我要评论

【原创】转载请注明作者Johnthegreat和本文链接。


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


方案一思路:

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):
        if re.search('(\d+)\)\.', file_name) is None:
            file_name = file_name.replace('.', '(0).')
        else:
            current_number = int(re.findall('(\d+)\)\.', 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!')

结果如下:


方案二思路:

来自(https://blog.csdn.net/yyly2012/articlehttps://img.qb5200.com/download-x/details/79106554)

1. 使用os.path.isfile判断文件是否存在
2. 使用递归函数判断
3. 添加编号时, 使用可变list 传值n=[0]

import os

def check_filename_available(filename):
    n=[0]
    def check_meta(file_name):
        file_name_new=file_name
        if os.path.isfile(file_name):
            file_name_new=file_name[:file_name.rfind('.')]+'_'+str(n[0])+file_name[file_name.rfind('.'):]
            n[0]+=1
        if os.path.isfile(file_name_new):
            file_name_new=check_meta(file_name)
        return file_name_new
    return_name=check_meta(filename)
    return return_name
with open(check_filename_available('t.txt'),'w') as f:
    f.write('Checking func!')

方案二使用了闭包函数来实现,也很巧妙。


以上都是通用型代码,直接在代码里面添加这个函数就可以用了,有问题欢迎联系我。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们