In my Python program, I write some content into a file, then I attempt to read the file and print it back out to the user. The data is written to the file successfully, however when I do f.read()
, an empty string is returned to the console.
Here is my current code:
f = open("test.txt", 'w+')
f.write("YOOO!!!")
data = f.read()
print(data)
f.close()
Does anyone know the issue? Thank you.
You have to reset the file pointer before reading.
Just add
f.seek(0)
before read()
is called
If you don't, it tries to read from the position of the end of the last write, which is the end of the file if the file is new. Thus, it returns nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With