0

Reading a file gives empty string (Python)

Here is my code: path = input('Enter file path: ') with open(path, 'a+') as file print(file.read()) while True: add = input('Enter text: ') file.write(add) print(file.read()) repeat = input('Do you want to keep writing? ') if repeat == 'yes': continue elif repeat == 'no': break I am able to create files and add text to it but reading only gives a blank string.

8th May 2017, 3:59 PM
Swapnodip
Swapnodip - avatar
3 Respuestas
+ 5
@James: He/she provide instruction for reading the file and print the content ( print(file.read() ) @Swapnodip Chakrabarti: Appart the missing colon ( : ) at end of the 'with' statement line, your code is working for me ( QPython3 / android )... printing the last writen text. If you want to print all the text file, you need to seek at the file begining before printing/reading ( file.seek(0) ), as the read pointer seems to be positionned at file end, and not updated by the write operation. Maybe the behaviour is different on your device/os? If it is, you can try to use the file.tell() method wich return the position in the file, to save the position before writting, and seeking to it after ( before reading )...
9th May 2017, 5:04 AM
visph
visph - avatar
0
@visph Adding file.seek(0) worked. Thanks for pointing that out.
9th May 2017, 11:16 AM
Swapnodip
Swapnodip - avatar