Search code examples
pythonpython-3.xstringfor-loopio

Regarding the new line characters .txt files contains when we are reading them in using the IO in Python


I am a beginner in Python and been playing around with what I know so far and came across the below problem. Can someone kindly help me out to understand why this occurs?

suppose I have a text named 'test.txt' file that contains the following,

This is the first line
This is the second line
This is the third line

I print every line in this text file by doing as below,

with open('test.txt', 'r') as f:
    for line in f:
        print(line)

However though, the output we get is,

This is the first line

This is the second line

This is the third line

As shown above we get an empty line printed due to each line in the text file containing a '\n' at the end of the each line.

To get rid of the empty line that is printed above, I know we could do something like,

with open('test.txt', 'r') as f:
    for line in f:
        print(line, end='')

This gives us the following output,

This is the first line
This is the second line
This is the third line

What I do not understand is, how have we been able to get rid of the newline character just by adding an empty string to the end of each line?


Solution

  • Note that '\n' is the default parameter given to end. This is from the official python docs: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False).
    You can check the docs here: https://docs.python.org/3/library/functions.html#print