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.
str.format()function, and/or 'f-strings'. This will make your string concatenation much simpler, rather than the JS format currently being used.