can only concatenate list (not "str") to list

Asked

Viewed 535 times

0

Hello, I’m new in python and programming I’m probably having a problem that should be very conceptual.I made this code to read a numerical sequence in a txt and rename it with the sequence found.

name_files3 = os.listdir(path_txt)

for TXT in name_files3:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(?:\d(?:[\s,.\-\xAD_]|(?:\\r)|(?:\\n))*){17}', content.read())
    if search is not None:
        name3 = search.group(0)
        # name3 = name3.replace("\n", "")
        # name3 = name3.replace("-", "")
        # name3 = name3.replace("\\", "")
        # name3 = name3.replace(".", "")
        # name3 = name3.replace(".", "")
        # name3 = name3.replace("/", "")
        # name3 = name3.replace(" ", "")
        fp = os.path.join("17_digitos", [letter for letter in name3 if letter.isdigit()] + "_%d.txt")
        postfix = 0
        while os.path.exists(fp % postfix):
            postfix += 1
        os.rename(
            os.path.join(path_txt, TXT),
            fp % postfix
        )

At first I was using the function replace remove all characters that appeared between numbers before renaming. It turns out that there are characters in Unicode that "seem" hyphenate but are not, so at the time of renaming some cases it was not working. So I used [letter for letter in name3 if letter.isdigit()] just to get the numbers that come up. It returns this error:

    fp = os.path.join("17_digitos", [letter for letter in name3 if letter.isdigit()] + "_%d.txt")
TypeError: can only concatenate list (not "str") to list

I tried to turn name3 into string and didn’t solve much

  • Does your text file have only 1 line? The one containing the text that will rename the file.

  • @Marlysson txt has many lines of text, the script finds in the middle of this text the numerical sequences I need.

  • Would it be all numbers? Get them and join them into a single string that would be the file name.. That’s it?

  • Yes, the number I am already able to remove from the text, even was being able to rename without problems like this: "Fp = os.path.Join("17_digits", name3 + "_%d.txt")" but it turns out I wasn’t able to get all the characters between the numbers with the replace function, so I decided to change even to try to improve the code and not use this lot of replace

  • 1

    You tried to use regex in name3 itself like this: re.sub(r" D","",name3) so it will remove anything that is not a string number.

  • worked very well, thank you!!

  • 1

    I’ll put it to her as an answer then you confirm it, in case someone else has the same problem.

Show 2 more comments

1 answer

1


Use regex on own name3 thus:

re.sub(r"\D","",name3) 

This will remove anything that is not a string number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.