June 27, 2022

tempfile Module in Python - Create Temporary File and Directory

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()
Output
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[0])
    print('File Path:'. fp[1])
    try:
        with os.fdopen(fp[0], '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[1])
Output
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() 
Output
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()
Output
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()
Output
created temporary directory F:/knpcode/Python\tmpswqxki5spy

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

No comments:

Post a Comment