For i uses only the last variable - Python

Asked

Viewed 54 times

0

Good morning!

I am with a project that I am improving and would like to make a For i to run all variables within the project, but when running it applies the project only to the last variable.

Code:

for i in ['1', '2', '3']:

    arquivo5 = open(r'\Texto para SAS\Vers' + str(i) + '.txt', 'w')

with open(r'\DataMining Python\Respostas.txt') as stream:
    with open(r'\Texto para SAS\teste.txt', 'r') as arq:

        palavras = arq.readlines()


        for line in stream:
                for word in palavras:

                    if word.lower() in line.lower():

                        a = (line.strip(), '¬', word + '\n\r')

                        arquivo5.writelines(a)
                        print(i)


arquivo5.close()

Reply.txt:

Muita cobranca para meu time
Cobrar nao e viver
Nao me cobre por isso

test.txt

cobra 
cobranca

1 answer

3


Because of indentation, your for only runs the assignment line to arquivo5. In the end, you modified arquivo5 three times before entering the with, then when you enter the with it executes only once with the last assigned value.

Just modify the indentation to include the logic inside the for:

for i in ['1', '2', '3']:
    arquivo5 = open(r'\Texto para SAS\Vers' + str(i) + '.txt', 'w')   

    with open(r'\DataMining Python\Respostas.txt') as stream:
        with open(r'\Texto para SAS\teste.txt', 'r') as arq:        
            palavras = arq.readlines()        
            for line in stream:
                    for word in palavras:

                        if word.lower() in line.lower():

                            a = (line.strip(), '¬', word + '\n\r')

                            arquivo5.writelines(a)
                            print(i)
    arquivo5.close()

Some improvements I would suggest to your code:

  • Trade the ['1', '2', '3'] for a range. Thus, you can increase the number of files without having to spend keyboard by typing a list.

  • Instead of using the open and close, use the with, like you’re doing with the other files. This creates a context manager, and ensures that your file will be closed properly no matter what happens inside the block.

Would something like this:

for i in range(1, 4):  # Inclui o 1, não inclui o 4
    with open(r'\Texto para SAS\Vers' + str(i) + '.txt', 'w') as arquivo5:
        with open(r'\DataMining Python\Respostas.txt') as stream:
            with open(r'\Texto para SAS\teste.txt', 'r') as arq:  
                palavras = arq.readlines()

                for line in stream:
                    for word in palavras:

                        if word.lower() in line.lower():
                            a = (line.strip(), '¬', word + '\n\r')

                            arquivo5.writelines(a)
                            print(i)

Browser other questions tagged

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