Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tempfile to create a sub-directory for all of my tempfiles

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.

like image 857
sutee Avatar asked Jan 13 '12 19:01

sutee


People also ask

What is the purpose of Tempfile module?

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.

What does Tempfile do in R?

Description. tempfile returns a vector of character strings which can be used as names for temporary files.

How do I write a Tempfile?

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.


2 Answers

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
like image 62
tharen Avatar answered Sep 21 '22 04:09

tharen


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....

like image 43
Has QUIT--Anony-Mousse Avatar answered Sep 23 '22 04:09

Has QUIT--Anony-Mousse