Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a temporary directory and get its path/ file name?

How can I create a temporary directory and get its path/file name in Python?

like image 706
duhhunjonn Avatar asked Jul 11 '10 15:07

duhhunjonn


People also ask

How do you create a temporary folder?

Open your File Explorer (it's usually the first button on your desktop taskbar, looks like a folder). Go to the "This PC" section on the left, and then double-click your C: drive. On the Home tab at the top, click "New Folder" and name it "Temp".

How do you create a directory named tmp files in the current working directory?

To create new directory use "mkdir" command. For example, to create directory TMP in the current directory issue either "mkdir TMP" or "mkdir ./TMP". It's a good practice to organize files by creating directories and putting files inside of them instead of having all files in one directory.

What is the name of temporary file?

Alternatively referred to as a foo file, a temporary file or temp file is a file created to hold information while a file's being created or modified. After the program is closed, the temporary file is deleted.


2 Answers

Use the mkdtemp() function from the tempfile module:

import tempfile import shutil  dirpath = tempfile.mkdtemp() # ... do stuff with dirpath shutil.rmtree(dirpath) 
like image 141
Philipp Avatar answered Oct 07 '22 01:10

Philipp


In Python 3, TemporaryDirectory from the tempfile module can be used.

From the examples:

import tempfile  with tempfile.TemporaryDirectory() as tmpdirname:      print('created temporary directory', tmpdirname)  # directory and contents have been removed 

To manually control when the directory is removed, don't use a context manager, as in the following example:

import tempfile  temp_dir = tempfile.TemporaryDirectory() print(temp_dir.name) # use temp_dir, and when done: temp_dir.cleanup() 

The documentation also says:

On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

At the end of the program, for example, Python will clean up the directory if it wasn't removed, e.g. by the context manager or the cleanup() method. Python's unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.

like image 24
Nagev Avatar answered Oct 07 '22 00:10

Nagev