Kamyar Souri
Kamyar Souri

Reputation: 1923

Read file in Python

I am new to Python and trying to learn the language structure.

I understand how for statement and open function work. But cannot explain how this piece of code works, which dumps the content of file sample_log.txt to screen:

for line in open("sample_log.txt"):
    print line

These are my questions:

  1. Does open return a list?
  2. When the file actually gets read to memory?
  3. Does the file gets read line by line or all at once?

Upvotes: 3

Views: 1216

Answers (1)

tlehman
tlehman

Reputation: 5167

The open function returns a file object, they are iterable, so you can loop over it using a for expression.

Upvotes: 4

Related Questions