Python tempfile module learning notes (temporary file)

  • 2020-04-02 13:42:04
  • OfStack

Tempfile as expected. TemporaryFile

If your application needs a TemporaryFile to store data, but does not need to share it with other programs, creating temporary files using the TemporaryFile function is the best option. Other applications cannot find or open this file because it does not reference the file system table. Temporary files created with this function are automatically deleted when closed.

Example 1:


import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid()
temp = open(filename, 'w+b')
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()
    os.remove(filename)     # Clean up the temporary file yourself

print
print 'TemporaryFile:'
temp = tempfile.TemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()  # Automatically cleans up the file

This example illustrates the difference between the normal way of creating a file and the TemporaryFile(). Note that a file created with TemporaryFile() does not have a filename

Output:


$ python tempfile_TemporaryFile.py

Building a file name yourself:
temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/guess_my_name.14932.txt

TemporaryFile:
temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>
temp.name: <fdopen>

 

The file is created by default with w+b permissions on any platform, and the program can read and write to it. This example illustrates the difference between the normal way of creating a file and the TemporaryFile(). Note that a file created with TemporaryFile() does not have a filename



$ python tempfile_TemporaryFile.py
Building a file name yourself:
temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/guess_my_name.14932.txt
TemporaryFile:
temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>
temp.name: <fdopen>

The file is created by default with w+b permissions on any platform, and the program can read and write to it.

Example 2:


import os
import tempfile

temp = tempfile.TemporaryFile()
try:
    temp.write('Some data')
    temp.seek(0)

    print temp.read()
finally:
    temp.close()

To write, you need to use seek() in order to read the data later.

Output:


$ python tempfile_TemporaryFile_binary.py
Some data

If you want the file to run in text mode, change the mode to 'w+t' when you create it.

Example 3:


import tempfile

f = tempfile.TemporaryFile(mode='w+t')
try:
    f.writelines(['firstn', 'secondn'])
    f.seek(0)

    for line in f:
        print line.rstrip()
finally:
    f.close()

Output:

$ python tempfile_TemporaryFile_text.py
first
second

Tempfile as expected. NamedTemporaryFile

If a temporary file is used by multiple processes or hosts, creating a named file is the easiest way. That's what NamedTemporaryFile does, and you can access its name using the name attribute


import os
import tempfile

temp = tempfile.NamedTemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    # Automatically cleans up the file
    temp.close()
print 'Exists after close:', os.path.exists(temp.name)

Even though the file has a name, it is automatically deleted after close

Output:


$ python tempfile_NamedTemporaryFile.py
temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>
temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0zHZvX
Exists after close: False

Tempfile as expected. Mkdtemp

Create temporary directory, this does not say more, see the example directly:


import os
import tempfile

directory_name = tempfile.mkdtemp()
print directory_name
# Clean up the directory yourself
os.removedirs(directory_name)

The output

$ python tempfile_mkdtemp.py
/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmpB1CR8M


Note: directories need to be removed manually.

Predicting Names

Use 3 parameters to control the filename, and the name generation formula: dir + prefix + random + suffix

Example:


import tempfile

temp = tempfile.NamedTemporaryFile(suffix='_suffix', 
                                   prefix='prefix_', 
                                   dir='/tmp',
                                   )
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()

Output:


$ python tempfile_NamedTemporaryFile_args.py

temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/prefix_UyCzjc_suffix

Tempfile as expected. Mkstemp ([suffix = '[, prefix =' TMP '[, dir = None [, text = False]]]])

      The mkstemp method is used to create a temporary file. This method is only used to create a temporary file, and after calling the tempfile.mkstemp function, returns a tuple with two elements, the first indicating the level of security to operate on the temporary file and the second indicating the path to the temporary file. The parameters suffix and prefix mean the suffix and prefix of the temporary file name, respectively. Dir specifies the directory where the temporary files are located. If no directory is specified, the temporary files will be saved according to the Settings of the system environment variables TMPDIR, TEMP or TMP. The parameter text specifies whether to manipulate the file as text. The default is False, which means to manipulate the file as binary.

Tempfile as expected. Mktemp ([suffix = '[, prefix =' TMP '[, dir = None]]])

      Mktemp returns the path to a temporary file, but does not create the temporary file.

Tempfile as expected. Tempdir

      This property is used to specify the default folder in which the temporary files (folders) are created. If the property is not set or set to None, Python returns the following environment variables TMPDIR, TEMP, and the directory specified by TEMP. If these environment variables are not defined, the temporary file is created in the current working directory.

Tempfile as expected. Gettempdir ()

      Gettempdir () is used to return the path to the folder where the temporary files are stored.

 


Related articles: