简体   繁体   English

如何不在不同的操作系统路径中覆盖 python 中的文件

[英]how to not overwrite file in python in different os path

so i want to avoid overwrite the file name that existed.所以我想避免覆盖存在的文件名。 but i don't know how to combine the code with mycode.但我不知道如何将代码与 mycode 结合起来。 please help me请帮我

here's my code for write file:这是我的写文件代码:

def filepass(f):
    print(f)
    with open ('media/pass/'+'filepass.txt', 'a') as fo:
        fo.write(f)
        fo.close()
    return fo

and here's the code to create number in name filepass:这是在名称 filepass 中创建数字的代码:

def build_filename(name, num=0):
    root, ext = os.path.splitext(name)
    print(root)
    return '%s%d%s' % (root, num, ext) if num else name

def find_next_filename(name, max_tries=20):
    if not os.path.exists(name): return name
    else:
        for i in range(max_tries):
            test_name = build_filename(name, i+1)
            if not os.path.exists(test_name): return test_name
        return None

all i want is to create filename: filepass.txt, filepass1.txt, filepass2.txt我只想创建文件名:filepass.txt、filepass1.txt、filepass2.txt

Something like this?是这样的吗?

def filepass(f):
    print(f)
    filename = find_next_filename('media/pass/filepass.txt')
    with open (filename, 'a') as fo:
        fo.write(f)
        # you don't need to close when you use "with open";
    # but then it doesn't make sense to return a closed file handle
    # maybe let's return the filename instead
    return filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM