Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file in Python

Tags:

python

file

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?
like image 466
Kamyar Souri Avatar asked Jan 24 '26 10:01

Kamyar Souri


1 Answers

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

like image 197
tlehman Avatar answered Jan 26 '26 00:01

tlehman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!