0
I’m having a problem that may be quite trivial but I’m not getting it. I found in a text by regular expression a numerical sequence of type XXXX/YYYY, after that I need to rename the file . txt with the sequence found. The problem is that when trying to rename the file python returns an error because it cannot 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’s giving some error that I’m 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'>
ie match='82121991', shows that to remove the bar replace worked
Why did you convert the
search
for string insearch = str(search)
? This doesn’t make much sense. If you need to remove the bar, you should do this after capturing the value of the group withsearch.group
.– Woss