Let’s say that I open a file, that didn’t previously exist, for writing:
f = open('/tmp/test.txt', 'w')
Once this line is executed the file ‘/tmp/test.txt’ is created. What is the cleanest way to remove (delete) the file with only the file object (f) and not the path?
You cannot remove a file handle, only a file path, since multiple paths can refer to the same file and some files (like sockets) don’t even have paths. Therefore:
However, you should not do that – there’s a better way to solve your problem. Use the tempfile module which deletes the file automatically, or just write to
/dev/nullif you just need a file handle and don’t care about the content being written.