I've been using tempfile.mkdtemp
with a prefix to create my temp files. This results in a lot of different directory in my tmp folder with 'tmp/myprefix{uniq-string}/
'.
I would like to change this and have a subdirectory so that my the temp folders I create are all under one main directory so that the prefix is actually a subfolder of tmp
'tmp/myprefix/{uniq-string}/
'.
Also, I don't want to override tempfile
's system for defining a default tmp directory.
I tried playing with the 'prefix
' and 'dir
' parameters but with no success.
Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.
Description. tempfile returns a vector of character strings which can be used as names for temporary files.
If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.
To use the dir argument you have to ensure the dir folder exists. Something like this should work:
import os
import tempfile
#define the location of 'mytemp' parent folder relative to the system temp
sysTemp = tempfile.gettempdir()
myTemp = os.path.join(sysTemp,'mytemp')
#You must make sure myTemp exists
if not os.path.exists(myTemp):
os.makedirs(myTemp)
#now make your temporary sub folder
tempdir = tempfile.mkdtemp(suffix='foo',prefix='bar',dir=myTemp)
print tempdir
Works for me. Did you create the tmp
folder beforehand?
>>> import tempfile
>>> tempfile.mkdtemp(dir="footest", prefix="fixpre")
OSError: [Errno 2] No such file or directory: 'footest/fixpregSSaFg'
Looks like it does try to create a subfolder of footest
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With