Tag Archives: iterate a file in Python

How to iterate over the contents of a file in Python

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

Continue reading