2

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)

matt
  • 41
  • 1
  • 4
  • This post can explain how to check if a file exists in python https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python – locus2k Nov 21 '17 at 18:12
  • 1
    It would be helpful if you could show the contents of one of the files in the `TXT` directory. –  Nov 21 '17 at 18:24

2 Answers2

0

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
)
TT--
  • 2,956
  • 1
  • 27
  • 46
MarAja
  • 1,547
  • 4
  • 20
  • 36
-1

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()
vasia
  • 1,093
  • 7
  • 18
  • The way to check whether a file exists is [`os.path.exists(path)`](https://docs.python.org/3/library/os.path.html#os.path.exists) or `os.path.isfile(path)`. –  Nov 21 '17 at 18:17