1
Let’s assume 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 prints(print).
1
Let’s assume 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 prints(print).
10
The most pythonic to accomplish this task is through a context manager with the with
.
with open("arquivo.txt") as file:
for line in file:
print line
With the context manager, you don’t have to worry about closing the file at the end, as it is guaranteed that it will be properly closed at the end of the with
. Also, it is worth commenting that the return of the function open
is a generator and can be iterated line by line, not needing to store all the file contents in memory - this makes a lot of difference depending on the file size.
Thank you Anderson! D
@Guilhermelima I invite you to do the [tour] by the site and read the guide What should I do if someone answers my question?
Thanks, I’m doing the Tour :D
2
It opens the file as read-only 'r', loads all lines in the Arq variable and prints 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()
Thank you very much :D
Browser other questions tagged python python-2.7
You are not signed in. Login or sign up in order to post.
You are using python 2 or 3?
– Wictor Chaves
Using python 2.7
– Luan pedro