user8314628
user8314628

Reputation: 2042

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?

Upvotes: 2

Views: 185

Answers (2)

user459872
user459872

Reputation: 24562

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. 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()

Also as recommended within the comments it's better to use context managers which will clean up the resources automatically.

Upvotes: 4

Jai248
Jai248

Reputation: 1649

When you open a file with a+ mode, the file stream will be positioned at the end of the file. Call f.seek( 0 ) where f is a file object created with open( ... ) before you create your DictReader. See this question for a more detailed discussion about this issue.

f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()

and for with open

with open(file_name, "a+") as f:
    f.write("hello world\n")
    f.seek(0)
    print(f.read())

Upvotes: 2

Related Questions