How to return series of values in Python

0

I have a function that reads line by line a TXT file to disk and formats it extracting only what interests me, getting a list like this:

Swi 04/11/2018 Basel Lugano 3 2 2 0
Swi 03/11/2018 Grasshopper Young Boys 0 3 0 0
Swi 04/11/2018 Luzern Zürich 2 5 1 2
Swi 04/11/2018 Sion St. Gallen 0 1 0 1

What is the best way to return this list? Save to disk (CSV or JSON) or do you have some Python framework that I can do this?

It will be used by another file .py . Remember that this list can reach more than 300 lines.

    
asked by anonymous 07.11.2018 / 10:08

1 answer

7

To read a file and move through the lines you can use the open function with the context manager defined by with :

with open('arquivo.txt') as arquivo:
    for linha in arquivo:
        print(linha)

As you need to format the line data, you can do something like:

with open('arquivo.txt') as arquivo:
    for linha in arquivo:

        # SUA LÓGICA DE FORMATAÇÃO AQUI

        print(resultado)

Or, as commented out, you can put this inside a function and return a generator using the term yield :

def linhas_formatadas(caminho):
    with open(caminho) as arquivo:
        for linha in arquivo:

            # SUA LÓGICA DE FORMATAÇÃO AQUI

            yield resultado

This would be enough to do:

for linha_formatada in linhas_formatadas('arquivo.txt'):
    print(linha_formatada)

Or, if you need to write to another file, it would look something like:

with open('resultado.txt', 'w') as resultado:
    for linha_formatada in linhas_formatadas('arquivo.txt'):
        resultado.write(linha_formatada)
    
07.11.2018 / 11:33