Using tempfile to create a subdirectory for all my tempfiles

I used tempfile.mkdtemp with a prefix to create temporary files. This leads to a lot of different directories in my tmp folder with ' tmp/myprefix{uniq-string}/ '.

I would like to change this and have a subdirectory so that my temporary folders that I create are under the same main directory, so the prefix is ​​actually a subfolder of tmp ' tmp/myprefix/{uniq-string}/ '.

Also, I don't want to override the tempfile system to define the default tmp directory.

I tried playing with the " prefix " and " dir " options, but without success.

+4
source share
2 answers

To use the dir argument, you must make sure that 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 
+10
source

It works for me. Did you create the tmp folder in advance?

 >>> import tempfile >>> tempfile.mkdtemp(dir="footest", prefix="fixpre") OSError: [Errno 2] No such file or directory: 'footest/fixpregSSaFg' 

Looks like he's trying to create a footest subfolder ....

+1
source

Source: https://habr.com/ru/post/1390903/


All Articles