Skip to content

Instantly share code, notes, and snippets.

@sligodave
Last active November 23, 2023 07:29
Show Gist options
  • Save sligodave/6539531 to your computer and use it in GitHub Desktop.
Save sligodave/6539531 to your computer and use it in GitHub Desktop.
Quick example of creating, using and deleting a temp file in python
import os
import tempfile
file_descriptor, file_path = tempfile.mkstemp(suffix='.tmp')
# You can convert the low level file_descriptor to a normal open file using fdopen
with os.fdopen(file_descriptor, 'w') as open_file:
open_file.write('hello')
# OR without the 'with'
open_file = os.fdopen(file_descriptor, 'w')
open_file.write('hello')
open_file.close()
# OR without the open low level file_descriptor
os.close(file_descriptor)
open_file = open(file_path, 'w')
open_file.write('hello')
open_file.close()
# You are responsibile for deleting your temp file
os.unlink(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment