Opening file for append ISSUE
Hi all, I have an issue that I absolutely cannot get around. When I run my script in the app, it works perfectly fine. Everything is normal. When I call my app through Safari it still runs normally, with the exception that it refuses to append to another file.
So to be clear: the only problem is when accessing the closed app using Pythonista://CoordinatesGet.py?action=run it doesn't write to my file. It DOES write to my file if I call it again, with the app already open, and it DOES write to my file when running the program normally from within the app. Here is my code:
theFile = open('CoordinatesList.txt','a')
print 'Coordinates:',latitude, longitude
I really appreciate the help! I'm starting to think it's a bug.
As far as I can tell your code never actually flushes (write to disk) or closes the file. This means that any changes will not be visible until
theFileis removed (which happens when you run a new script, because then Pythonista will wipe the Python environment by default). When working with files it's usually best to use the
withstatement, which will ensure that the file is always properly written and closed:
with open("some_file.txt", "a") as f: f.write("some text\n") # ... any code that uses the file (f) ... print("Done!")
Note that the file object (
f) can only be used inside the
withblock. Once that block is exited,
fbecomes unusable. This means that any code that uses
fneeds to be in the
(By the way, see this link on how to post code blocks on the forums.)
Not sure if this what you after @Oak. I am very new, but still trying to help as many help me. So take it with a grain of salt
import location, os.path __FILE_DIR__ = os.path.expanduser('~/Documents/') __FNAME__ = 'CoordinatesList.txt' __MY_FILE__ = __FILE_DIR__ + __FNAME__ if not os.path.exists(__MY_FILE__): theFile = open(__MY_FILE__, 'w') is_new_file = '' else: theFile = open(__MY_FILE__, 'a') is_new_file = '\n' location.start_updates() myCoords=location.get_location() location.stop_updates() longitude=str(myCoords['longitude']) latitude=str(myCoords['latitude']) theFile.write(is_new_file) theFile.write(longitude) theFile.write('\n') theFile.write(latitude) theFile.close()
I thinks the issue might be not closing the file across calls.
import location,time location.start_updates() mycoords = location.get_location() location.stop_updates() with open('coordinates.txt','a') as fh: fh.write(str(mycoords)+'\n'+str(time.ctime())+'\n')
This worked fine for me, but did keep jumping back to pythonista rather than remaining in Safari. Also to better format your code for markdown, use the following approach:
your code snippet here
in your posts to the forum
Thank you all, you were most certainly right! File was not closing. I have fixed it now by simply using <code> with open </code> for the file.
Talk about great minds think alike!!!