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.
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.
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>
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()