Home > Mobile >  how to not overwrite file in python in different os path
how to not overwrite file in python in different os path

Time:12-02

so i want to avoid overwrite the file name that existed. but i don't know how to combine the code with 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:

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

CodePudding user response:

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
  • Related