How do I read python row by line?

1

Let's suppose I have a txt file with some data:

[File.txt]

Oie
Olá
Tudo bem?

I want something (in python) that reads line by line and print.

    
asked by anonymous 26.09.2017 / 18:05

2 answers

7

The most pythonico way to accomplish this task is through a < a href="https://docs.python.org/2/library/stdtypes.html#typecontextmanager"> context manager with with .

with open("arquivo.txt") as file:
    for line in file:
        print line

With the context manager, you do not have to worry about closing the file at the end because it is guaranteed that it will be properly closed at the end of with . Also, worth mentioning is that the open function return is a generator and can be iterated line by line, not needing to store all the contents of the file in memory - this makes a lot of difference depending on the size of the file. p>

What is with in Python?

    
26.09.2017 / 18:15
1

It opens the file as read-only 'r', loads all lines in variable arq and printa line by line:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
arq = open('arquivo.txt', 'r')
texto = arq.readlines()
for linha in texto :
    print(linha)
arq.close()
    
26.09.2017 / 18:11