Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not reading file correctly

Tags:

python

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.

like image 438
NodeReact020 Avatar asked Oct 12 '25 01:10

NodeReact020


1 Answers

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.

like image 64
gelonida Avatar answered Oct 14 '25 16:10

gelonida