Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

# 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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading