Save everything I print in my Python file to a new file

0

Good I have the following code that looks for a number in this column and then prints some lines that are above and below:

                import collections
                import sys
                import itertools
                with open(archivo.txt) as f:
                    before = collections.deque(maxlen=3)
                    for line in f:
                        if "UN_NRO" in line[50:60]:
                            sys.stdout.writelines(before)
                            sys.stdout.write(line)
                            sys.stdout.writelines(itertools.islice(f, 10))
                            break
                        before.append(line)

I need to save all those lines in another file "summary.txt" I appreciate your help

    
asked by Giacomo F 18.10.2018 в 14:03
source

1 answer

0

You can open two files, one to read and one to write, in the same context (line with ) and then use both within. To write use fichero.write() or fichero.writelines() .

That is, in your case:

vote against Favourite Good I have the following code that looks for a number in this column and then prints some lines that are above and below:

import collections
import sys
import itertools
with open("archivo.txt") as entrada, open("resultado.txt", "w") as salida:
    before = collections.deque(maxlen=3)
    for line in entrada:
        if "UN_NRO" in line[50:60]:
            salida.writelines(before)
            salida.write(line)
            salida.writelines(itertools.islice(f, 10))
            break
        before.append(line)

I have corrected a bug that you had, because archivo.txt you had put it without quotes. I have not entered either to assess what you do within the loop, since you have not explained what is expected as a result, but I find it very rare and far-fetched (surely it can be done without collections or itertools ).

    
answered by 18.10.2018 в 16:33