You cannot delete the file descriptor, only the file path, since several paths can refer to the same file and some files (for example, sockets) do not even have paths. Therefore:
import os f = open('/tmp/test.txt', 'w') os.unlink(f.name)
However, you should not do this - there is a better way to solve your problem. Use the tempfile module, which automatically deletes the file or simply writes to /dev/null
if you just need a file descriptor and don't care about the written content.
source share