#1
input_file = 'my-textfile.txt'
current_file = open(input_file)
print current_file.readline()
print current_file.readline()
#2
input_file = 'my-textfile.txt'
print open(input_file).readline()
print open(input_file).readline()
Why is it that #1 works fine and displays the first and second line, but #2 prints 2 copies of the first line and doesn’t print the same as #1 ?
When you call
openyou are opening the file anew and starting from the first line. Every time you callreadlineon an already open file it moves its internal “pointer” to the start of the next line. However, if you re-open the file the “pointer” is also re-initialized – and when you callreadlineit reads the first line again.Imagine that
openreturned afileobject that looked like this:When you ran your first example you would get something like the following output:
While the output of your second example would look something like this: