I'm learning how to work with files in Python using Jupyter notebook. Why do I have to use open() each time to print what I'd like to?

Question:

I tried:

my_file = open("test.txt")
for line in my_file:
    print("Here it says: " + line)
    
lines = my_file.readlines()
print(lines[1])

But the second print command did not print anything.
then I tried:

my_file = open("test.txt")
for line in my_file:
    print("Here it says: " + line)
    
my_file = open("test.txt")
lines = my_file.readlines()
print(lines[1])

and the second print command printed correctly. Why do I have to use open() each time?

Asked By: Vlungz

||

Answers:

# See comments in line.
fi = open("test.txt", 'w')
for n in range(10):
    fi.write(str(n))
fi.close()

my_file = open("test.txt")
for line in my_file:
    print("Here it says: " + line)
# The file indicates there are no more lines by setting the EOF
# End of file marker
lines = my_file.readlines() # reads the same end of file marker.
print(lines[1])
Answered By: Carl_M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.