Issue
I'm quite new to Python and Pi'ing, and would like some help with appending a text file on a Raspberry Pi. My script will call a GET or a POST REST API and write the time, status and reason for each call.
I got the call information from grepit's comment in Simple URL GET/POST function in Python and it works great.
For appending my file, I use the following code:
#...Some working code...
dateNow = datetime.datetime.now()
string = ("\n" + dateNow.strftime("%c") + " - " + str(response.status) +
": " + response.reason + "\n")
with open('MyCallLog.txt', 'a+') as file:
file.write(string)
What I have read regarding similar issues, is that the file is not closed or flushed. However, if I try to debug using print(file.read())
outside the 'with' I get an error that is file is already closed and debugging inside the with displays nothing. I also tried it without the with and specifically stating file.close()
. I have debugged the string variable using print(string)
and it displays as intended.
Any suggestions?
Final notes:
- I am aware that opening a file as 'a+' does open it in read and write mode. This is currently only for my debugging purposes.
Solution
When a file is opened in append mode using "a+"
the cursor is positioned at the end of the file. That is why a call to .write()
will append to the end of the file instead of overwriting it.
When you call file.read()
in the with
block, it is reading the file from the last character onwards, which is why your print output is empty.
To print the content you need to seek to the beginning of the file.
with open("myfile.txt", "a+") as file:
file.write("some_text")
file.seek(0)
print(file.read()) # "some_text"
Better yet, just open the file again for your debugging.
with open("myfile.txt", "a+") as file:
file.write("some_text")
with open("myfile.txt", "r") as file:
print(file.read())
Your code to append was actually correct. There should be a file in the CWD with all of your attempts in it.
Also, the reason that you get an error when you try to call .read()
outside of the with
block is because file.close()
is implicitly called when the block exits.
open()
returns a context manager. You can read about context managers in python here. They are very useful and great to know about. I write new context managers often at my job.
Answered By - Blake Smith