Renaming file: 'str' object has no attribute 'group' [closed]

0

I have a problem that may be very trivial but I can not understand. I found in a text by regular expression a number sequence of type XXXX / YYYY, after that I need to rename the .txt file with the sequence found. The problem is that when trying to rename the file python returns an error because it can not rename a file that has a "/".

    import os
    import re
    import random
    import string


    # Endereco da pasta em que os documentos se encontram
    path_txt = (r'''C:\Users\mateus.ferreira\Desktop\TXT''')

name_files = os.listdir(path_txt)

for TXT in name_files:
    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())
        search = str(search)
        search = search.replace("/","")
    if search is not None:
        os.rename(os.path.join(path_txt, TXT),
                  os.path.join("Processos3", search.group(0) + "_" + str(random.randint(100, 999)) + ".txt"))

I tried to use the replace function but it is giving some error that I am not understanding why:

      File "C:/Users/mateus.ferreira/PycharmProjects/untitled/classificador_reclamante.py", line 50, in <module>
    os.path.join("Processos3", search.group(0) + "_" + str(random.randint(100, 999)) + ".txt"))
AttributeError: 'str' object has no attribute 'group'

When I do a print after replace it returns:

<_sre.SRE_Match object; span=(7449, 7458), match='82121991'>

that is match = '82121991', it shows that to remove the bar the replace worked

    
asked by anonymous 21.11.2017 / 12:16

1 answer

0

You are converting the return of the function search to string meaninglessly.

for TXT in name_files:
    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())
        search = str(search)
        search = search.replace("/","")
    if search is not None:
        os.rename(os.path.join(path_txt, TXT),
                  os.path.join("Processos3", search.group(0) + "_" + str(random.randint(100, 999)) + ".txt"))

It is even working with the value of search even before checking whether it is null or not. If the intention is to remove the bars from the value searched by the regular expression, you must first capture the group and only then replace, not the other, as you did.

It would be something like:

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:  # Verifica se o valor foi encontrado
        name = search.group(0)  # Captura o valor do grupo
        name = name.replace('/', '')  # Substitui a barra
        os.rename(...)  # Renomeia utilizando o valor de 'name'
    
21.11.2017 / 13:37