0

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

import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')


name_files = os.listdir(path_txt)


for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()

Its creating .txt's empty in the "Processes" folder, but named the way I need it.

ps: using Python 3

  • `open` will create a *new file* with the given name, it won't rename your file. You should look at [`os.rename`](https://stackoverflow.com/questions/2759067/rename-multiple-files-in-a-directory-in-python), you just need a small tweak from what you've got at the moment. – hnefatl Nov 16 '17 at 23:22

1 Answers1

0

You are not renaming the files. Instead you are opening a file in write mode. If the file does not already exist it will be created.

Instead you want to rename the file:

# search the file for desired text
with open(os.path.join(path_txt, TXT), "r") as content:
    search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())

# we do this *outside* the `with` so file is closed before rename
if search is not None:
    os.rename(os.path.join(path_txt, TXT), 
        os.path.join("Processes" , search.group(0) + ".txt"))
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • Thanks for your help. Now it returns another error: Traceback (most recent call last): File "", line 7, in FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\ I think because he found a document with a repeated sequence. In that case how do I rename it? for example: 1234 .... copy (1) ; 1234 .... copy (2); –  Nov 17 '17 at 00:48