For i uses only the last variable - Python

0

Good morning!

I have a project that I am improving and would like to do a For i to run all the variables within the project, however 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()

Response.txt:

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

test.txt

cobra 
cobranca
    
asked by anonymous 26.04.2018 / 15:20

1 answer

2

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

Simply change the indent to include the logic within 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 that I would suggest to your code:

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

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

It would look 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)
    
26.04.2018 / 16:06