-4

If you're using the tempfile library, then you might have experienced the scenario where the temporary file is not being automatically deleted even your program has completed. This is quite crucial for programs which would be used multiple times as its directory will get messy once the temporary files pile up.

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
Kucosyn
  • 29
  • 5

1 Answers1

-2

This is Q&A. Hence, here's my solution.

Apparently, the default settings for the tempfile.TemporaryFile does not automatically delete your temporary file, but adding a prefix in your tempfile.NamedTemporaryFile works:

with tempfile.NamedTemporaryFile(prefix="anything_",
                                         dir=os.getcwd()) as tempf:

            '''put something'''
            tempf.seek(0)

Notes:

  • The os.getcwd() is to get the current directory of your file.
  • Your temporary file would be anything_ + (random values) (i.e anything_23mem)

Hope it helps.

Kucosyn
  • 29
  • 5
  • 2
    What was the question? – Scott Hunter Sep 28 '17 at 01:06
  • This sounds like a bug report for the Python folks, not a Stack Overflow question. Neither your problem, nor your solution, makes any sense at all. I've never needed to provide a `prefix` to trigger automatic deletion on `with` block exit, nor have I ever failed to auto-delete (aside from cases where `ctypes` or an extension actually crashed the interpreter bypassing cleanup). If this works at all, it would likely be the explicit use of the working directory as a storage location (possibly because something is wrong with permissions on your `TEMP` storage directory), not related to `prefix`. – ShadowRanger Sep 28 '17 at 01:07
  • @ShadowRanger I was suspicious that the automatic deleting of the temporary files in my `TEMP` folder is not working. So I went to that directory (after running my script), and I still saw them there. The next thing I did to make sure that I can monitor it easily is to make the `dir` of the temporary file the same with the directory of the script. Also, I am using admin of the PC. So I tried running the script, it worked, but the temp file remained. And that's why I'm sharing my "solution" if ever there would be anyone out there who would experience the same. – Kucosyn Sep 28 '17 at 04:20