I’m enjoying learning Python 3 the hard way. I’m now playing around with exercise 20 and have run into something I don’t understand.
I’ve condensed exercice 20:
from sys import argv
script, input_file = argv
def print_a_line(f):
_ print(f.readline())_
current_file = open(input_file)
print(“Let’s print three lines:”)
print_a_line(current_file)
print_a_line(current_file)
print_a_line(current_file)
What I see:
$ python3.6 ex20a.py test.txt
Let’s print three lines:
This is line 1
This is line 2
This is line 3
I tried to shorten the code by ‘embedding’ the open function and the readline function in the print command. Here’s my new code:
from sys import argv
script, input_file = argv
print(“Let’s print three lines:”)
print(open(input_file).readline())
print(open(input_file).readline())
print(open(input_file).readline())
What I expected was that this would give exactly the same result as the original code, however what I see:
$ python3.6 ex20b.py test.txt
Let’s print three lines:
This is line 1
This is line 1
This is line 1
Why does the first code print the first three lines of the input_file whereas the second code prints the first line of the input_file three times?
I hope you can help me grasp what’s happening and why the two codes give different output. I appreciate your help very much!
Many thanks and best wishes from Amsterdam, the Netherlands.
Berend