How to Iterate over Lines of File in Python


Mastery of file input and output operations is a crucial skill for a software engineer, as reading data from a file is something every programmer needs to know how to do. The process of reading data from a file requires iterating over each line of text until the end-of-file symbol is reached. The Python programming language contains built-in features for iterating over lines of a file. You can create a simple Python script that can accomplish this in a few minutes.

Things You'll Need

  • PC with Python Programming Language (see Resource for download link)
  • Open the IDLE text editor that comes with the Python programming language.

  • Select "File/Save As" from the main menu and save the file as ""

  • Write or copy the following line of code to open up any text file for processing. In this example, you will load the text contained in the source code file itself.

    f = open("")

  • Iterate over the lines of text inside the text file by writing the following for loop:

    for line in f.readlines():

  • Indent the next line by pressing "tab" and write the print function to print out each line in the text file, like this:


  • Press "F5" to execute the script. The output will be the source code you just wrote:

    f = open("")

    for line in f.readlines():


Related Searches


Promoted By Zergnet



You May Also Like

  • How to Read a CSV File in Python

    Python is a powerful scripting language with a large collection of useful tools in its standard libraries. Among these useful tools is...

  • How to Extract a Zip File With Python

    Python is an open license programming language available in Windows, Linux and Mac, plus Java .Net virtual machines. Python features three versions,...

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!