Home > OS >  Misunderstanding how end= argument works in print() function in a while loop
Misunderstanding how end= argument works in print() function in a while loop

Time:08-30

Hi so I just started learning how to read files in Python. So, I started writing a file using Python using the code:

with open('dog_breeds.txt', 'w') as writer:
    writer.write("Pug\r\nJack Russell Terrier\r\nEnglish Springer Spaniel\r\nGerman Shepherd\r\nStaffordshire Bull Terrier\r\nCavalier King Charles Spaniel\r\nGolden Retriever\r\nWest Highland White Terrier\r\nBoxer\r\nBorder Terrier\r\n")
    writer.close()

This results in a .txt file which image can be seen here.

Then, I start to run the following code:

import time
reader = open('dog_breeds.txt', 'r ')
line = reader.readline()
print('Output of readline while loop is: ')
while line != '':
    print(line, end='')
    time.sleep(1)
    line = reader.readline()
reader.close()

Then, I got this output when I execute the code:

Output of readline while loop is:
Pug

Jack Russell Terrier

English Springer Spaniel

German Shepherd

Staffordshire Bull Terrier

Cavalier King Charles Spaniel

Golden Retriever

West Highland White Terrier

Boxer

Border Terrier

So, I am a little confused. I thought that the end = '' argument in the print() will cause each line in the .txt file to be printed at the end of the previous line that is printed, resulting in one long line being displayed (i.e. PugJackRussellTerrierEnglish...). Instead, what is displayed is multiple lines with each line in the .txt file being a separate line. Is there something I am misunderstanding?

CodePudding user response:

By default python uses a new line in print.(print has end="\n" as default value)

your file uses \r\n for each line so if you try to print it line by line in a loop with normal print (without end="")

it would print something like this format:

*first_line_in_file
*new empty line because you have \r\n
*new empty line because python print(end="\n")
*second line
...

but now with end="" it's like this:

*first_line_in_file
*new empty line because you have \r\n
*second line
...

Conclusion: end="" doesn't remove \n from your text it just stops python from adding extra \n to your output.

CodePudding user response:

I don't know if you are using Windows, but when I ran your code:

with open('dog_breeds.txt', 'w') as writer:
    writer.write("Pug\r\nJack Russell Terrier\r\nEnglish Springer Spaniel\r\nGerman Shepherd\r\nStaffordshire Bull Terrier\r\nCavalier King Charles Spaniel\r\nGolden Retriever\r\nWest Highland White Terrier\r\nBoxer\r\nBorder Terrier\r\n")

On my Windows machine, the line break \r\n creates two line breaks:

Pug

Jack Russell Terrier

English Springer Spaniel

German Shepherd

Staffordshire Bull Terrier

Cavalier King Charles Spaniel

Golden Retriever

West Highland White Terrier

Boxer

Border Terrier

So when you start reading the file, even though you print using the end='' parameter, there will still be an extra new line.

To overcome this, you need to check if the line has data while stripping it and then print it, if the line has data, example:

with open('dog_breeds.txt') as reader:
    for line in reader:
        if line.rstrip(): # if the stripped line has data
            print(line.rstrip(), end='')

Result:

PugJack Russell TerrierEnglish Springer SpanielGerman ShepherdStaffordshire Bull TerrierCavalier King Charles SpanielGolden RetrieverWest Highland White TerrierBoxerBorder Terrier

CodePudding user response:

Here's something that will work on both Unix and Windows systems:

import re

FILE = 'dog_breeds.txt'

with open(FILE, 'w') as writer:
    writer.write("Pug\r\nJack Russell Terrier\r\nEnglish Springer Spaniel\r\nGerman Shepherd\r\nStaffordshire Bull Terrier\r\nCavalier King Charles Spaniel\r\nGolden Retriever\r\nWest Highland White Terrier\r\nBoxer\r\nBorder Terrier\r\n")

with open(FILE) as reader:
    print(re.sub('[\r\n]', '', reader.read()))

Output:

PugJack Russell TerrierEnglish Springer SpanielGerman ShepherdStaffordshire Bull TerrierCavalier King Charles SpanielGolden RetrieverWest Highland White TerrierBoxerBorder Terrier

CodePudding user response:

This written script can execute as you want:

import time
reader = open('dog_breeds.txt', 'r ')
line = reader.readline()
print('Output of readline while loop is: ')
for i in reader:
    line = i.rstrip("\n")
    if line:
        print(line)
        time.sleep(1)
reader.close()

pay attention to the .replace("\n", "").

The result of running the above code is the following output:

Output of readline while loop is: 
Jack Russell Terrier
English Springer Spaniel
German Shepherd
Staffordshire Bull Terrier
Cavalier King Charles Spaniel
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier

And each line will be printed after one second as you intended in your code.

CodePudding user response:

https://docs.python.org/3/library/functions.html#print

"Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end."

  • Related