How to Iterate over Lines of File in Python

Save

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 "textIterator.py."

  • 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("textIterator.py")

  • 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:

    print(line)

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

    f = open("textIterator.py")

    for line in f.readlines():

    print(line)

References

Promoted By Zergnet

Comments

Resources

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

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