user2971015
user2971015

Reputation: 51

Reading a file on python

my_file = open('file.txt')
next_line = my_file.readline()
while next_line != "":
    print(next_line)
    next_line = my_file.readline()

This code is correct and it reads one line in a file at a time. My question is why do they use next_line!= '' what does this mean? Then they also say next_line = my_file.readline, what is the purpose of doing that, i don't understand the entire loop.

My other question is how can I change this code so it doesn't skip a line when it prints the lines on a file?

Upvotes: 0

Views: 58

Answers (1)

riamse
riamse

Reputation: 351

while next_line != "" means "while the line is not empty". So, the loop means "print next_line and set next_line to the next line until next_line is empty. When next_line is empty, exit the loop".

Calling .readline() on a file object leaves a "\n" at the end. So you're actually printing the line + \n, which is why it appears to skip a line.

Try using print(next_line[:-1]). This will print every character except for the last one (\n).

Upvotes: 1

Related Questions