You're reading all the lines from the file, but you're not outputting them. If you want to print the lines to standard output, you need to use print()
as you did in your first example.
You can also write this somewhat more elegantly using contexts and more iterators:
from pathlib import Path
file = Path('test.txt')
with file.open() as open_file:
for line in open_file:
print(line, end="")
test.txt:
Spam
Spam
Spam
Wonderful
Spam!
Spamity
Spam
Result:
Spam
Spam
Spam
Wonderful
Spam!
Spamity
Spam
Using a context for opening the file (with file.open()
) means you inherently set up closing the file, and the iterator for the lines (for line in open_file
) means you're not loading the whole file at once (an important consideration with larger files).
Setting end=""
in print()
is optional depending on how your source files are structured, as you might otherwise end up printing extra blank lines in your output.