3

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?
1
  • 3
    You should consider reading the documentation on File Objects and the open() function! Commented Dec 9, 2011 at 22:51

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Now I get it. So when the file get read and is it line by line or all at once?
@kamyar, line by line. This is good because it means you can easily process really big files without needing to load them into memory at once
@KamyarSouri you could also read the entire file in one time : docs.python.org/tutorial/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.