Python Forum
Opening file and outputting its text content example - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Opening file and outputting its text content example (/thread-30204.html)



Opening file and outputting its text content example - leodavinci1990 - Oct-12-2020

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()


RE: Opening file and outputting its text content example - buran - Oct-12-2020

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.