In this tutorial we’ll see how to create temporary file and directory in Python. You may require a temporary file to store some data temporarily while the application is running which can be safely deleted automatically when the task is done.
tempfile module in Python
In Python, tempfile module has functions to create temporary files and directories. It works on all supported platforms.
Following functions are there in tempfile module for creating temporary file.
1. tempfile.TemporaryFile()– This function returns an object that can be used as a temporary storage area. File is opened in w+b mode by default so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms. Temporary file is destroyed as soon as it is closed. Here is a Python example to create a temporary file and write content to it.
def create_temp_file(): fp = tempfile.TemporaryFile() fp.write(b'Writing content in temp file') print('Temp file full name:', fp.name) fp.seek(0) # read temp file s = fp.read() print(s) fp.close()
Temp file full name: C:\Users\knpcode\AppData\Local\Temp\tmpigwrmggh b'Writing content in temp file'
2. tempfile.NamedTemporaryFile– This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system.
3. tempfile.mkstemp– Creates a temporary file in the most secure manner possible. With this function user is responsible for deleting the temporary file when done with it. mkstemp() returns a tuple containing an OS-level handle to an open file and the absolute pathname of that file, in that order.
def create_temp_file(): fp = tempfile.mkstemp() print('Handle:', fp) print('File Path:'. fp) try: with os.fdopen(fp, 'w+') as tmp: tmp.write('Writing content in temp file') tmp.seek(0) # read temp file s = tmp.read() print(s) finally: os.remove(fp)
C:\Users\Anshu\AppData\Local\Temp\tmp8yajie7g Writing content in temp file
Functions in tempfile module for creating temporary directory.
1. tempfile.TemporaryDirectory– This function securely creates a temporary directory. Directory is created in the default location if no argument is passed, you can also pass the directory location using the dir paramater.
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. The directory can be explicitly cleaned up by calling the cleanup() method.
def create_temp_dir(): fp = tempfile.TemporaryDirectory() print('created temporary directory', fp.name) fp.cleanup() create_temp_dir()
created temporary directory C:\Users\Anshu\AppData\Local\Temp\tmp44habknw
When directory is passed using dir parameters
def create_temp_dir(): fp = tempfile.TemporaryDirectory(dir='F:/knpcode/Python') print('created temporary directory', fp.name) create_temp_dir()
created temporary directory F:/knpcode/Python\tmpmkt8363n
2. tempfile.mkdtemp– Creates a temporary directory in the most secure manner possible. With this function user is responsible for deleting the temporary directory and its contents when done with it. mkdtemp() returns the absolute pathname of the new directory.
def create_temp_dir(): fpath = tempfile.mkdtemp(suffix='py', dir='F:/knpcode/Python') print('created temporary directory', fpath) # removing temp dir os.rmdir(fpath) create_temp_dir()
created temporary directory F:/knpcode/Python\tmpswqxki5spy
- fnmatch Module in Python – File Name Pattern Matching
- Input from User in Python – input() function
- Python Program to Check File or Directory Exists
- Python Program to Delete Files Having a Specific Extension
- Python Program to Write a File
- Python Program to Append to a File
- Python Classes and Objects
- Name Mangling in Python With Examples
That’s all for the topic tempfile Module in Python – Create Temporary File and Directory. If something is missing or you have something to share about the topic please write a comment.
You may also like