I have a question regarding the with open as context manager when opening a .txt file.
I have a file with the following contents:
Hello there!
Is everyone ok today?
Let’s get started.
To open the file, I use the following script:
from pathlib import Path
FILE_PATH = Path('/Users/my_pc/Desktop/tester.txt')
with open(FILE_PATH, "r", encoding = 'UTF-8') as f:
for line in f:
print(line, end='') # Prints as per the file
# print(line) # Adds two empty lines between text lines
As noted per the comments, depending on which print statement that I use, it either prints as is or it adds two extra empty lines between text lines. Why does it add two extra text lines when using the second print option?
Python does read the lines as they are in the file. Sometimes you want to keep the line endings, other times you don’t, so it’s better to keep them and let you remove them if you don’t want them.
Ok, that is if one iterates using a for loop statement to read each line one at a time so as not to overburden memory at once. But if there are no memory constraints, I suppose one can just use the following to read the file contents in one reading (no for loop) :
A better design of print() is that it prints whatever was asked to print only, no more, no less. Why to predict the next printing is going to start a new line or not? Let each print() do its own business.
It’s not a prediction. print is designed to do this, because it’s a useful thing to do. That’s the same reason that you can give it multiple things to print, and it will put spaces in between (and you can disable the spaces using sep, the same way that you would disable the newline using end). It’s also the same reason that it accepts non-string inputs and converts them for you.
If you want the lower-level interface, “here is one string, write it out without changing or adding anything” - that is sys.stdout.write, as Chris says. It works because the standard output is available as sys.stdout, and that output stream is just like a text file open for writing (except there is no actual file on disk).
OK, I agree with you. print() was designed to ease its most usage cases and, for those rare situation, it let user to disable the extra stuff it had put in. Thank you for providing a different viewing angle of this design.