Skip to content Skip to sidebar Skip to footer

Rename A File That Already Exists

I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequen

Solution 1:

Replace:

os.rename(
    os.path.join(path_txt, TXT),
    os.path.join("Processos3", name3 + "_" + str(random.randint(100, 999)) + ".txt")
)

With:

fp = os.path.join("Processos3", name3 + "_%d.txt")
postfix = 0whileos.path.exists(fp % postfix):
    postfix += 1os.rename(
    os.path.join(path_txt, TXT),
    fp % postfix
)

Solution 2:

The code below iterates through the files found in the current working directory, and looks a base filename and for its increments. As soon as it finds an unused increment, it opens a file with that name and writes to it. So if you already have the files "foo.txt", "foo1.txt", and "foo2.txt", the code will make a new file named "foo3.txt".

import os
filenames = os.listdir()

our_filename = "foo"
cur = 0
cur_filename = "foo"
extension = ".txt"while(True):
    if (cur_filename) in filenames:
         cur += 1
         cur_filename = our_filename + str(cur) + extension
    else:
         # found a filename that doesn't exist
         f = open(cur_filename,'w')
         f.write(stuff)
         f.close()

Post a Comment for "Rename A File That Already Exists"