3

This is what I'm using now....

    import tempfile
    import json

    with tempfile.NamedTemporaryFile(suffix='.json') as tf:
        json.dumps(jsonKey)
        keyPath = tf.name

I looking for a way to create a temporary file that will be automatically removed when execution/session will finish (even if it will be errored)

P.S. Without using file.remove() it should be auto removed!

Oksana Ok
  • 515
  • 3
  • 7
  • 19
  • I'm confused, what you describe is already the default behavior, see https://docs.python.org/3/library/tempfile.html (`delete` has default value `True`) – CherryDT Jul 27 '21 at 15:17
  • [Here](https://stackoverflow.com/questions/46459373/python-3-4-temporary-files-not-being-deleted-automatically) someone had a similar issue but with the old version Python 3.4, there the fix (workaround?) was to use a `prefix`. – CherryDT Jul 27 '21 at 15:21
  • ...Okay I guess your point is that when you crash, it's not deleted. Well, you shouldn't crash, so it's best to start by adding appropriate error handling. You could use `delete=False` and instead manually delete the file in a `finally` handler. – CherryDT Jul 27 '21 at 15:24
  • delete=True is default... but I need to use this file for a session , so I use `delete=False` not sure how to remove it after – Oksana Ok Jul 27 '21 at 15:25
  • 1
    Hm but your example doesn't show `delete=False`. Also I realize now your example doesn't even dump the data to `tf`. Can you please edit it? It's confusing otherwise. - You could keep an array of such files (or use a whole temp directory that you can then delete as a whole) and delete the files in an [`atexit`](https://docs.python.org/3/library/atexit.html) handler - is that what you need? – CherryDT Jul 27 '21 at 15:27
  • If you want to also handle `SIGTERM` (normally `atexit` doesn't run in that case) you can check [this answer](https://stackoverflow.com/a/40866947/1871033) – CherryDT Jul 27 '21 at 15:28
  • Switch from `NamedTemporaryFile` to just `TemporaryFile` (so it's unlinked immediately on-creation and the blocks will be freed when the refcount hits zero after there are no remaining file handles) and stop using `.name` if you need it to go away on crash. Why do you need `keyPath` at all? If your OS is Linux, you can often use `f'/proc/{os.getpid()}/fd/{tf.fileno()}'` instead of having a real filename at all. – Charles Duffy Jul 27 '21 at 15:32
  • Try this: `write` the data from json.dumps() to the temporary file `tf`. use try catch finally blocks and inside finally close the temporary file object. It will make sure that file is deleted when session is over or error is occured. – Himatkumar Purohit Jul 27 '21 at 16:12

0 Answers0