+ 1
Problem reading a written file on Android on QPython (python3).
I wrote a small program while learning about file.write, and while it writes to the file (I found it with a file manager), the print() doesn't print anything when I run it in the QPython terminal. file1 = open("test1.txt", "a+") file1.write("Ayyyy, it worked!") cont = file1.read() print(cont) file1.close() Any idea why?
4 Réponses
+ 2
I changed it a little and now it works:
file1 = open("test1.txt", "a+")
file1.write("Ayyyy, it worked!")
file1 = open("test1.txt", "r")
cont = file1.read()
print(cont)
file1.close()
maybe a+ is no good for reading from the start.
+ 2
Konoha Tomono-Duval No, .read call dont reopened in write mode ("a+" mode is for append mode with read support). Like i said before, you trying to read at end of file, for this .read return an empty string. Like my previous hint you can simply do:
import os
file1 = open("test1.txt", "a+")
file1.write("Ayyyy, it worked!")
# this set the current file
# "pointer" to beginning
file1.seek(0, os.SEEK_SET)
cont = file1.read()
print(cont)
file1.close()
and all its fine
+ 1
Konoha Tomono-Duval Your problem is that you try to read at end of file (then read return empty). You have 2 option:
1) Close and reopen file for reading
2) Use seek method for read from start. At example by putting this line after .write
file1.seek(0, os.SEEK_SET)
This line set the internal file pointer to beginning of file allowing you to read from start
+ 1
Tried Paul's method, and it worked. I guess that a+ doesn't read, or maybe the file1.read reopened it in write mode and deleted the contents. Thanks, y'all!