Could someone tell me the benefit of a tempfile
in python, and in which case should I use it?
I'm coding a program to process a file, and it will first call another script to process the file first, generating a temporary file and do next step which I'll code myself.
I'm wondering if I write the temporary file directly to disk using fh.write()
and then after whole program delete them, or I should use tempfile
module to create a tempfile
to store it?
The tempfile module allows a script to create temporary files and directories. It handles all the boilerplate code dealing with creating a random, unique filename and deleting the file when the file object is no longer referenced. It is also cross-platform and portable, so there is no hassle when deciding where to put the file (/tmp
, ./
, etc.).
If you want to create a temporary "file" in RAM, you can use StringIO class from the io module. You can initialise the "file" with the data (e.g. StringIO("your data")
), and then it will act just like a file (with read
, write
, etc.).