How do I make python read line by line?

Asked

Viewed 11,713 times

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

  • You are using python 2 or 3?

  • Using python 2.7

2 answers

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.

What’s with no Python for?

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

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