How to return Python value series

Asked

Viewed 90 times

0

I have a function that reads line by line a TXT file on disk and format 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 have some structure in Python that I can do this?

'Cause it’s gonna be used by another file .py. Remembering that this list may have more than 300 lines.

  • 2

    Search for generator in Python, using yield

  • uses json same that is standard anywhere.

  • Thanks Anderson Carlos Woss, what I want is this

1 answer

7


To read a file and go through the lines you can use the function open 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, 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 way it would be enough to do:

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

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

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

Browser other questions tagged

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