I'm using tempfile.mkstemp()[1]
in some class frequently. I'm doing some operations on the created file and then delete it.
I'm not using context manager with with
or smth like that, just using the filename.
Obviously, tempfile.mkstemp()
returns a tuple of opened file object and the filename. I'm only using filename and not even accessing file object, of course.
I'm wondering if that is causing leaking open file handler when execution is leaving particular method? Or is file object somehow silently closed?
I'm using tempfile.mkstemp()[1]
in some class frequently. I'm doing some operations on the created file and then delete it.
I'm not using context manager with with
or smth like that, just using the filename.
Obviously, tempfile.mkstemp()
returns a tuple of opened file object and the filename. I'm only using filename and not even accessing file object, of course.
I'm wondering if that is causing leaking open file handler when execution is leaving particular method? Or is file object somehow silently closed?
Share Improve this question asked Jan 29 at 14:19 LetMeSOThat4ULetMeSOThat4U 6,82810 gold badges58 silver badges102 bronze badges 2- Why are you asking? Are you just curious or is your program long-running and draining your system of memory? – jsf80238 Commented Jan 29 at 14:57
- I'm asking because a. leaking resources is bad programming practice and so b. it's unprofessional. – LetMeSOThat4U Commented Jan 29 at 18:38
1 Answer
Reset to default 1Yes, you're leaking file handles.
The handle is a numeric file descriptor. They're not unique and there's no way for the garbage collector to know when the reference is gone, so it can't close the file automatically.
You could use os.fdopen()
to create a Python file object that references this handle. When this is closed, the file handle will also be closed. You can use a context manager for this, or let it be closed automatically by GC.