Disclaimer: I know I essentially answer my own question, but please humor me anyway.
I'm working through a Python book I have (Python Crash Course 2nd Edition), and it says, "The only difference between this output and the original file is the extra blank line at the end of the output. The blank line appears because read() returns an empty string when it reaches the end of the file; this empty string shows up as blank line. If you want to remove the extra blank line, you can use rstrip() in the call to print()." That is the exact wording they use in the book. However, when I do what they tell me to do, no blank line is printed.
All of my code:
with open('/workspaces/functions/files_exceptions/pi_digits.txt', encoding='utf-8') as file_object:
contents = file_object.read()
print(contents)
print("Hello World!") # To show a newline is not printed
Everything in the file I'm reading from:
3.1415926535
8979323846
2643383279
Output:
3.1415926535
8979323846
2643383279
Hello World!
The output the book shows (the underlines are meant to represent a blank line (Stack Overflow won't let me include a blank line as code)):
3.1415926535
8979323846
2643383279
____________
As you can see, there is no trailing newline printed by Python. Does it not do this anymore? I know Python is now in version 3.12, so I'm wondering if it's a recent change made to Python. It might not be though, because the VS Code repo I'm working in was created before the update (I don't know whether or not it updates automatically, or if you have to do it manually (and if so, how) (please tell me the answer to this)).
I don't think the book which you're quoting is correct. Whether or not
f.read()has a newline character at the end of the string which it returns is dependent on the contents of the file which is being read. Many text editors will add newlines at the end of text files, even if the user does not input them manually. I also use Visual Studio Code and my experience is that it does not enforce newlines at the end of files, so I think that a difference in editor or editor settings is the most likely explanation for your difference in behaviour.Observe the following test, in which I use
echo -nto create a file without a newline at the end, andechoto create a file with a newline at the end: