Python Forum

Full Version: Opening file and outputting its text content example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If the Python file below is run on a text file containing the following:

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!


Why does it return empty spaces in the output between each line of text-like below?

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!



f=open(r"C:\Users\.....\Documents\demofile.txt")
data=None
while data!="":
#If an empty string is returned,
#the file end is reached
    data= f.readline()
    print(data[:])
f.close()
when you read line from file it also read the new-line char at the end of the line. print() function also add new-line char at the end, so combined you have 2 new-line chars.
one way is to strip the new-line char from line using str.strip() method, the other is to pass end='' to print function.