10 February 2017

Snippet shows you how to write to temporary directory. You can either write a single file, or do stuff in a directory. In any case you should remove the files and folders after you have done your business, you don't want to clutter your /tmp folder.

Source code viewer
  1. import os
  2. import shutil
  3. import tempfile
  4.  
  5. # Temporary file.
  6. fd, filename = tempfile.mkstemp()
  7. try:
  8. # Do something with the temp file, like write into it.
  9. os.write(fd, your_content)
  10. os.close(fd)
  11. finally:
  12. # Delete the temporary file after usage.
  13. os.remove(filename)
  14.  
  15. # Temporary directory.
  16. # Create temporary directory for csv files.
  17. temp_dir = tempfile.mkdtemp()
  18. # Do your work...
  19. # Clean up the temporary directory.
  20. shutil.rmtree(temp_dir)
Programming Language: Python