Python--tempfile

Source: Internet
Author: User

The main functions are as follows:

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 other application is unable to find or open this file because it does not reference the file system table. Temporary files created with this function are automatically deleted when they are closed.

123456789101112131415161718192021 importosimporttempfileprint‘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.namefinally:    temp.close()    os.remove(filename)     # Clean up the temporary file yourselfprintprint ‘TemporaryFile:‘temp =tempfile.TemporaryFile()try:    print‘temp:‘, temp    print‘temp.name:‘, temp.namefinally:    temp.close()  # Automatically cleans up the file

This example illustrates the difference between a common method of creating a file and the Temporaryfile () Note: Files created with temporaryfile () do not have a file name

$ 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 with the W+b permission, which is the case in any platform, and the program can read and write to it.

1234567891011 importosimporttempfiletemp =tempfile.TemporaryFile()try:    temp.write(‘Some data‘)    temp.seek(0)        printtemp.read()finally:    temp.close()

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

$ python tempfile_temporaryfile_binary.py

Some data

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

1234567891011 import tempfilef =tempfile.TemporaryFile(mode=‘w+t‘)try:    f.writelines([‘first\n‘, ‘second\n‘])    f.seek(0)    forline inf:        printline.rstrip()finally:    f.close()

$ python tempfile_temporaryfile_text.py

First

Second

Tempfile. Namedtemporaryfile

If a temporary file is used by multiple processes or hosts, it is easiest to create a file with a name. This is what namedtemporaryfile to do, you can use the Name property to access its name

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

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

$ 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

Create a temp directory, this is not much to say, look directly at examples

1234567 importosimport tempfile directory_name = tempfile.mkdtemp()printdirectory_name# Clean up the directory yourselfos.removedirs(directory_name)

$ python tempfile_mkdtemp.py

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

The directory needs to be deleted manually.

Predicting Names

Use 3 parameters to control the file name, the name of the formula: Dir + prefix + random + suffix

1234567891011 importtempfiletemp =tempfile.NamedTemporaryFile(suffix=‘_suffix‘,                                    prefix=‘prefix_‘,                                    dir=‘/tmp‘,                                   )try:    print‘temp:‘, temp    print‘temp.name:‘, temp.namefinally:    temp.close()

$ 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 only used to create a temporary file , after calling the Tempfile.mkstemp function, returns a tuple containing two elements, the first element indicates the security level of the operation of the temporary file, 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 file resides, and if no directory is specified, the temp or TMP will be TMPDIRaccording to the system environment variable. Settings to save the temporary file, the parameter text specifies whether the file is manipulated as text, and the default is False, which indicates that the file is manipulated in binary form.

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

The mktemp is used to return the path to a temporary file, but the temporary file is not created.

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 will return the following environment variable tmpdir, TEMP, temp specified directory, and if these environment variables are not defined, temporary files will be created in the current working directory.

Tempfile.gettempdir ()

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

Python--tempfile

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.