Create temporary directory python

Generate temporary files and directories using Python

The tempfile module in standard library defines functions for creating temporary files and directories. They are created in special temp directories that are defined by operating system file systems. For example, under Windows the temp folder resides in profile/AppData/Local/Temp while in linux the temporary files are held in /tmp directory.

Following functions are defined in tempfile module

TemporaryFile()

This function creates a temporary file in the temp directory and returns a file object, similar to built-in open() function. The file is opened in wb+ mode by default, which means it can be simultaneously used to read/write binary data in it. What is important, the file’s entry in temp folder is removed as soon as the file object is closed. Following code shows usage of TemporaryFile() function.

>>> import tempfile >>> f = tempfile.TemporaryFile() >>> f.write(b'Welcome to TutorialsPoint') >>> import os >>> f.seek(os.SEEK_SET) >>> f.read() b'Welcome to TutorialsPoint' >>> f.close()

Following example opens TemporaryFile object in w+ mode to write and then read text data instead of binary data.

>>> ff = tempfile.TemporaryFile(mode = 'w+') >>> ff.write('hello world') >>> ff.seek(0) >>> ff.read() 'hello world' >>> ff.close()

NamedTemporaryFile()

This function is similar to TemporaryFile() function. The only difference is that a file with a random filename is visible in the designated temp folder of operating system. The name can be retrieved by name attribute of file object. This file too is deleted immediately upon closing it.

>>> fo = tempfile.NamedTemporaryFile() >>> fo.name 'C:\Users\acer\AppData\Local\Temp\tmpipreok8q' >>> fo.close()

TemporaryDirectory()

This function creates a temporary directory. You can choose the location of this temporary directory by mentioning dir parameter. Following statement will create a temporary directory in C:\python36 folder.

>>> f = tempfile.TemporaryDirectory(dir = "C:/python36") 

The created directory appears in the dir1 folder. It is removed by calling cleanup() function on directory object.

>>> f.name 'C:/python36\tmp9wrjtxc_' >>> f.cleanup()

mkstemp()

This unction also creates a temporary file, similar to TemporaryFile() function. Additionally, suffix and prefix parameters are available to add with temporary file created. Unlike in case of TemporaryFile(), the created file is not automatically removed. It should be removed manually.

>>> f = tempfile.mkstemp(suffix = '.tp') C:\Users\acer\AppData\Local\Temp\tmpbljk6ku8.tp

mkdtemp()

This function also creates a temporary directory in operating system’s temp folder and returns its absolute path name. To explicitly define location of its creation, use dir parameter. This folder too is not automatically removed.

>>> tempfile.mkdtemp(dir = "c:/python36") 'c:/python36\tmpruxmm66u'

gettempdir()

This function returns name of directory to store temporary files. This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.

>>> tempfile.gettempdir() 'C:\Users\acer\AppData\Local\Temp'

In this article functions in tempfile module have been explained.

Источник

Python Tempfile Module to Work with Temporary Files and Directories

Python Tempfile

In this tutorial, we’ll delve into the powerful Python tempfile module, an essential tool for creating, managing, and working with temporary files and directories in your applications.

This guide covers key module methods, such as TemporaryFile(), TemporaryDirectory(), and NamedTemporaryFile(), and how they enable secure and efficient handling of temporary data in a Python environment.

By understanding the tempfile module’s capabilities, you can harness its potential to enhance your software’s reliability and performance. Let’s get started!

The Python tempfile module lets you create and manage temporary files and directories easily. You can work with methods like TemporaryFile(), TemporaryDirectory(), or NamedTemporaryFile() to create temporary files and directories, which are automatically deleted when closed or when your program finishes.

Understanding the Tempfile Module in Python

This module is a part of the standard library (Python 3.x), so you don’t need to install anything using pip. You can simply import it!

We will look at how we can create temporary files and directories now.

Creating Temporary Files and Directories

The tempfile module gives us the TemporaryFile() method, which will create a temporary file.

Since the file is temporary, other programs cannot access this file directly.

As a general safety measure, Python will automatically delete any temporary files created after it is closed. Even if it remains open, after our program completes, this temporary data will be deleted.

Let’s look at a simple example now.

import tempfile # Create a temporary file using tempfile.TemporaryFile() temp = tempfile.TemporaryFile() # Retrieve the directory where temporary files are stored temp_dir = tempfile.gettempdir() print(f"Temporary files are stored at: ") print(f"Created a tempfile object: ") print(f"The name of the temp file is: ") # Close and clean up the temporary file automatically temp.close()
Temporary files are stored at: /tmp Created a tempfile object: The name of the temp file is: 3

Let’s now try to find this file, using tempfile.gettempdir() to get the directory where all the temp files are stored.

After running the program, if you go to temp_dir (which is /tmp in my case – Linux), you can see that the newly created file 3 is not there.

ls: cannot access '3': No such file or directory

This proves that Python automatically deletes these temporary files after they are closed.

Now, similar to creating temporary files, we can also create temporary directories using the tempfile.TemporaryDirectory() function.

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

The directory names are random, so you can specify an optional suffix and/or prefix to identify them as part of your program.

Again, to ensure safe deletion of the directory after the relevant code completes, we can use a context manager to securely wrap this!

import tempfile with tempfile.TemporaryDirectory() as tmpdir: # The context manager will automatically delete this directory after this section print(f"Created a temporary directory: ") print("The temporary directory is deleted")
Created a temporary directory: /tmp/tmpa3udfwu6 The temporary directory is deleted

Again, to verify this, you can try to go to the relevant directory path, which won’t exist!

Interacting with Temporary Files: Reading and Writing

Similar to reading or writing from a file, we can use the same kind of function calls to do this from a temporary file too!

import tempfile with tempfile.TemporaryFile() as fp: name = fp.name fp.write(b'Hello from AskPython!') # Write a byte string using fp.write() fp.seek(0) # Go to the start of the file content = fp.read() # Read the contents using fp.read() print(f"Content of file : ") print("File is now deleted")

Let’s now look at the output.

Content of file 3: b'Hello from AskPython!' File is now deleted

Indeed, we were able to easily read and write from/to temporary files too.

Working with Named Temporary Files

In some situations, named temporary files may be useful to make the files visible to other scripts/processes so that they can access it, while it is not yet closed.

The tempfile.NamedTemporaryFile() is useful for this. This has the same syntax as creating a normal temporary file.

import tempfile # We create a named temporary file using tempfile.NamedTemporaryFile() temp = tempfile.NamedTemporaryFile(suffix='_temp', prefix='askpython_') print(f"Created a Named Temporary File ") temp.close() print("File is deleted")
Created a Named Temporary File /tmp/askpython_r2m23q4x_temp File is deleted

Here, a named temporary file with a prefix of askpython_ and suffix of _temp is created. Again, it will be deleted automatically after it is closed.

Conclusion

In this guide, we explored the tempfile module in Python, which provides an efficient way to create and manage temporary files and directories. This powerful tool is crucial when handling temporary data in software applications. As a developer, how might you benefit from using temporary files in your projects?

References

Источник

Читайте также:  Sublime text автодополнение python
Оцените статью