0

I have a piece of code which would save a file and after once clicked the tkinter button for saving it, python saves it every 5 minutes. But you could also open the saved file: so I need a piece of code which first tries to close the file (if open) and then save it again. This is my code:

def save_changes():
    # first close the saved_file
    wb.save(saved_file)
    cur_time = datetime.datetime.now().strftime("%H.%M.%S")
    saved_label.config(text="laatst opgeslagen op:\n" + cur_time)
    saved_label.after(300000, save_changes)
  • 5
    Why isn't `save_changes` opening *and* closing the file? There doesn't seem to be any reason to leave it open between calls. – chepner Jan 17 '22 at 21:19
  • no there's a button to open that file, so you can see the changes. But when it must be saved after 5 minutes it must first be closed, if open –  Jan 17 '22 at 21:25
  • 1
    Just because you are displaying the contents doesn't mean the file needs to be open the entire time. – chepner Jan 17 '22 at 21:33
  • Are you looking to `flush()` changes to the file? – JonSG Jan 17 '22 at 21:33
  • You can have a button which opens a dialog to ask for a file path. But you do NOT NEED to open the file right away. Just store the file name on open button. Then open/save/close the file as @chepner mentioned. – MSH Jan 17 '22 at 21:34
  • 1
    What *is* `saved_file`? Is it a file name, a file-like object, something else? – chepner Jan 17 '22 at 21:34
  • 1
    I could clarify it a bit more: I run a tkinter program, which processes Excel files, but at some time you want to see what you changed and click on the open file button. After that it opens the file. But when you don't close the file, python couldn't save the (new) changes! That's the problem. So I wanted to let python try to close the file and save it afterwards! I have tried os.close but it returned an error: integer is required got a type string –  Jan 17 '22 at 21:49
  • 1
    Why are you using `os.close()` at all? That is not the correct method for closing open files. – John Gordon Jan 17 '22 at 21:50
  • You set up the event loop, with the `after` method, to call itself, which re-enables itself to be called later every 5 minutes. – Keith Jan 17 '22 at 21:56
  • This is a slightly different topic but does show how to close a file if you dont use the `with` pattern. https://stackoverflow.com/questions/29281291/explicitly-closing-files-in-python – TeddyBearSuicide Jan 17 '22 at 22:24
  • why I use os.close(): well, it's because I also use os.startfile bonded to the file open button. the only problem with os.close(): is that it gives the error mentioned above: So is there someone who could solve this problem? –  Jan 18 '22 at 09:02

0 Answers0