Python why file with content cannot be read?

Solution 1:

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.

Solution 2:

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