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