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

Python why file with content cannot be read?

import pathlib    
file_name = '%s/survey_ids.txt' % pathlib.Path(__file__).parent.resolve()
        
f = open(file_name, "a+")
f.write("hello world\n")
print(f.read())
f.close()

The first time I run the script, it creates the file survey_ids.txt and writes hello world\n to it. It doesn’t print anything for sure. But for the second time I run it, it writes another hello world\n to survey_ids.txt but doesn’t print anything still. I suppose it will print hello world\n. Why would this happen?

>Solution :

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

f.write advances the stream position. So when you read the file using f.read() it will try to read from current stream position to the end of the file.
So to get the expected behavior try to seek to byte offset 0 before the .read call.

f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
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