0

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.
njmouton
  • 15
  • 4
  • 1
    As an aside, have a look into string formatting using the `str.format()` function, and/or 'f-strings'. This will make your string concatenation much simpler, rather than the JS format currently being used. – S3DEV Feb 13 '21 at 20:36
  • Without seeing the whole function or more code I can't be certain what is going on. Perhaps if your script is continuously running you are always in the context manager? – im_baby Feb 13 '21 at 20:40
  • Try *just* the snippet you have above; I tried something similar (just a different string) and worked fine. (Also on a Pi). Just ensure you are looking at the file created in the *current* directory. – S3DEV Feb 13 '21 at 20:42

1 Answers1

1

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.

  • Nice answer, and kudos for mentioning the context manager details. – S3DEV Feb 13 '21 at 21:01
  • Great, thanks! So I have played around a bit, and it appears to be working in the actual file, but the file.seek(0) made that I couldn't see my changes (or any previous data) – njmouton Feb 15 '21 at 14:06