Python - File File iterators

Introduction

File iterators are best for reading lines

Content is strings, not objects

Files are buffered and seekable

Close is often optional: auto-close on collection

The following code begins by opening a new text file for output, writing two lines, and closing the file.

Then the code opens the same file in input mode and reads the lines back one at a time with read line.

The third readline call returns an empty string. And this is how Python file methods tell you that you've reached the end of the file.

Empty lines in the file come back as strings containing just a newline character, not as empty strings.

Demo

myfile = open('myfile.txt', 'w')        # Open for text output: create/empty 
myfile.write('hello text file\n')       # Write a line of text: string 
myfile.write('goodbye text file\n') 
myfile.close()                          # Flush output buffers to disk 
# from w w w.  java  2  s  .c  om
myfile = open('myfile.txt')             # Open for text input: 'r' is default 
print( myfile.readline() )                       # Read the lines back 
print( myfile.readline() )
print( myfile.readline() )                       # Empty string: end-of-file

Result