python – 一种无需覆盖即可创建文件和目录的方法

前端之家收集整理的这篇文章主要介绍了python – 一种无需覆盖即可创建文件和目录的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

你知道当你下载的东西和下载文件夹包含一个同名文件,而不是覆盖它或抛出错误时,文件最后会附加一个数字吗?例如,如果我想下载my_file.txt,但它已经存在于目标文件夹中,则新文件将命名为my_file(2).txt.如果我再试一次,它将是my_file(3).txt.

我想知道在Python 3.x中是否有办法检查并获得一个唯一的名称(不一定是创建文件或目录).我目前正在实现它:

import os
def new_name(name,newseparator='_')
    #name can be either a file or directory name

    base,extension = os.path.splitext(name)
    i = 2
    while os.path.exists(name):
        name = base + newseparator + str(i) + extension
        i += 1

    return name

在上面的示例中,如果cwd中已存在my_file.txt,则运行new_file(‘my_file.txt’)将返回my_file_2.txt. name也可以包含完整或相对路径,它也可以工作.

最佳答案
我会使用PathLib并按照以下方式做一些事情:

from pathlib import Path 

def new_fn(fn,sep='_'):
    p=Path(fn)
    if p.exists():
        if not p.is_file(): 
            raise TypeError
        np=p.resolve(strict=True)
        parent=str(np.parent)
        extens=''.join(np.suffixes)  # handle multiple ext such as .tar.gz
        base=str(np.name).replace(extens,'')
        i=2
        nf=parent+base+sep+str(i)+extens    
        while Path(nf).exists():
            i+=1
            nf=parent+base+sep+str(i)+extens    
        return nf   
    else:       
        return p.parent.resolve(strict=True) / p 

这只处理文件,但是相同的方法适用于目录(稍后添加).我将把它留作读者的项目.

原文链接:https://www.f2er.com/python/438933.html

猜你在找的Python相关文章