简体   繁体   中英

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 sequence of numbers of each one. I rename each file with the sequence I extracted from .txt

path_txt = (r'''C:\Users\user\Desktop\Doc_Classifier\TXT''')

for TXT in name_files3:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(([0-9]{4})(/)(([1][9][0-9][0-9])|([2][0-9][0-9][0-9])))', content.read())

    if search is not None:
        name3 = search.group(0)
        name3 = name3.replace("/", "")
        os.rename(os.path.join(path_txt, TXT),
                  os.path.join("Processos3", name3 + "_" + str(random.randint(100, 999)) + ".txt"))

I need to check if the file already exists, and rename it by adding an increment. Currently to differentiate the files I am adding a random number to the name (random.randint(100, 999))

PS: Currently the script finds "7526/2016" in .txt, by regular expression. Remove the "/". Rename the file with "75262016" + a random number (example: 7526016_111). Instead of renaming using a random number, I would like to check if the file already exists, and rename it using an increment (example: 7526016_copy1, 7526016_copy2)

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 = 0

while os.path.exists(fp % postfix):
    postfix += 1

os.rename(
    os.path.join(path_txt, TXT),
    fp % postfix
)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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