'Python not reading file correctly
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.
Solution 1:[1]
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.
Solution 2:[2]
It is happening because after writing content in the file, the file pointer comes at the end of the file and there's no content there. So, it is not printing anything. To overcome this problem, either you have to move your file pointer to the beginning or opening that file again.
To move file pointer-
f.seek(position)
put position = 0 if you want to go at the beginning of this file
- To close and open that file,
First writing content to our test.txt file and then reading content from it.
with open("test.txt", 'w+') as f:
f.write("YOOO!!!")
with open("test.txt", 'r') as f:
data = f.read()
print(data)
Solution 3:[3]
Just before opening the file, you can change the current working directory, which solved the issue in my case
os.chdir(r'path')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben Soyka |
| Solution 2 | |
| Solution 3 | Aashishk |
