Many times you need to work with files in Python. Let’s say that you have to iterate over the content of a file for further processing. You can use for this task the open
function which returns a file object that can be iterated over line by line.
First create a text file and name it file.txt
for example. I placed it on my desktop. Below is the content of the file:
Line 1
Line 2
Line 3
Let’s open the file and iterate over its content.
>>> file_opened = open('file.txt')
>>> for line in file_openrd:
... print(line)
...
Line 1
Line 2
Line 3
What is returned is an iterable function which can be used as any other iterator (usingnext()
for example).
>>> file_with_next = open('file.txt')
>>> next(file_with_next)
'Line 1\n'
>>> next(file_with_next)
'Line 2\n'
>>> next(file_with_next)
'Line 3'