In the last basic python programming language we showed how to use For loop to read text lines from a text file. In this blog post, we show how to read text lines using while loop.

Below is an example code to read text file using while loop:

while loop to read text files in Pythonf = open('mytext.txt')
while True:
    line = f.readline()
    if not line: break    print(line, end = '')

We have a file called mytext.txt stored in the computer. We create an instance/object called f from the open class and pass the name of the file as argument. The second argument r is optional. Then using the while loop we read the text by first creating a named variable called line to store the output from the return of f.readline( ). If there is no text then f.readline( ) will have nothing and so line is empty. In this case we break the loop and print the lines otherwise.

Following is the output:

Python programming language tutorial
text open/read tutorial

However, while loop is slower than for loop for reading lines. This is because when while loop is used the code is executed in as bytecode by python whereas when if loop is used the code is executed in C language.

To read how this file was initially created read the using For loop to read lines of texts from text files using python. To read about while loop basics read While statement in Python programming language.


Post a Comment