Python tempfile Module Learning notes (temporary files) _python

Source: Internet
Author: User

Tempfile. Temporaryfile

How your application needs a temporary file to store data, but does not need to be shared with other programs, creating temporary files with the Temporaryfile function is the best option. The file cannot be found or opened by other applications because it does not refer to the File system table. Temporary files created with this function are automatically deleted when they are closed.

Example one:

Copy Code code as follows:

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 a common method of creating a file and Temporaryfile (), noting that a file created with Temporaryfile () does not have a filename

Output:

Copy Code code as follows:

$ 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>


By default, a file is created using the W+b permission, as in any platform, and the program can read and write to it. This example illustrates the difference between a common method of creating a file and Temporaryfile (), noting that a file created with Temporaryfile () does not have a filename


Copy Code code as follows:

$ 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>

By default, a file is created using the W+b permission, as in any platform, and the program can read and write to it.

Example two:

Copy Code code as follows:

Import OS
Import Tempfile

temp = Tempfile. Temporaryfile ()
Try
Temp.write (' Some data ')
Temp.seek (0)

Print Temp.read ()
Finally
Temp.close ()

Write Hou, you need to use Seek (), in order to read the data later.

Output:

Copy Code code as follows:

$ python tempfile_temporaryfile_binary.py

Some data


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

Example three:

Copy Code code as follows:

Import Tempfile

f = tempfile. Temporaryfile (mode= ' w+t ')
Try
F.writelines ([' first\n ', ' second\n '])
F.seek (0)

For line in F:
Print Line.rstrip ()
Finally
F.close ()

Output:
Copy Code code as follows:

$ python tempfile_temporaryfile_text.py

The

Second

Tempfile. Namedtemporaryfile

If temporary files are used by multiple processes or hosts, creating a file with a name is the easiest way to do it. That's what namedtemporaryfile to do, you can access its name using the Name property

Copy Code code as follows:

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)

Although the file has a name, it will still be deleted automatically after close

Output:

Copy Code code as follows:

$ 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.mkdtemp

To create a temporary directory, this is not much to say, see examples directly:

Copy Code code as follows:

Import OS
Import Tempfile

Directory_name = Tempfile.mkdtemp ()
Print Directory_name
# Clean up the directory Yourself
Os.removedirs (Directory_name)

Output
Copy Code code as follows:

$ python tempfile_mkdtemp.py

/var/folders/9r/9r1t+tr02raxzk+f71q50u+++uw/-tmp-/tmpb1cr8m



Note: The directory needs to be manually deleted.

Predicting Names

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

Instance:

Copy Code code as follows:

import tempfile

temp = tempfile. Namedtemporaryfile (suffix= ' _suffix ',
                                     prefix= ' Prefix_ ',
                                     dir= '/tmp ',
                                     )
Try:
    print ' Temp: ', temp
    print ' temp.name: ', Temp.name
finally:
     Temp.close ()

Output:

Copy Code code as follows:

$ python tempfile_namedtemporaryfile_args.py


Temp: <open file ' <fdopen> ', Mode ' w+b ' at 0x1004481e0>

Temp.name:/tmp/prefix_uyczjc_suffix

Tempfile.mkstemp ([suffix= ' [, prefix= ' tmp ' [, dir=none[, Text=false]]]]

The Mkstemp method is used to create a temporary file. This method is used only to create temporary files, and after calling the Tempfile.mkstemp function, returns a tuple that contains two elements, the first element indicates the security level that the temporary file is manipulated, and the second element indicates the path to the temporary file. The parameters suffix and prefix represent the suffix and prefix of the temporary file name respectively; dir Specifies the directory where the temporary files are located, and if no directory is specified, the temporary files are saved according to the system environment variable Tmpdir, temp, or TMP settings The parameter text specifies whether the file is manipulated as text, and false by default, which indicates that the file is manipulated in binary form.

Tempfile.mktemp ([suffix= ' [, prefix= ' tmp ' [, Dir=none]]])

Mktemp is used to return the path to a temporary file, but does not create the temporary file.

Tempfile.tempdir

This property is used to specify the default folder where temporary files (folders) are created. If you do not set this property or set it to None,python, the following environment variables are returned TMPDIR, temp, temp Specifies the directory, and if these environment variables are not defined, the temporary files will be created in the current working directory.

Tempfile.gettempdir ()

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.