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:
Let’s open the file and iterate over its content.
>>> file_opened = open('file.txt')
>>> for line in file_openrd:
What is returned is an iterable function which can be used as any other iterator (using
next() for example).
>>> file_with_next = open('file.txt')