Python tempfile Module Learning notes (temp file)

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

Example one:
Copy the 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 the Temporaryfile () Note: Files created with temporaryfile () do not have a file name

Output:
Copy the Code code as follows:


$ python tempfile_temporaryfile.py


Building a file name yourself:

Temp

Temp.name:/tmp/guess_my_name.14932.txt


Temporaryfile:

Temp: ', mode ' w+b ' at 0x1004486f0>

Temp.name:


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


Copy the Code code as follows:


$ python tempfile_temporaryfile.py

Building a file name yourself:

Temp

Temp.name:/tmp/guess_my_name.14932.txt

Temporaryfile:

Temp: ', mode ' w+b ' at 0x1004486f0>

Temp.name:

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.

Example two:
Copy the 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, need to use Seek (), in order to read the data later.

Output:
Copy the Code code as follows:

$ python tempfile_temporaryfile_binary.py

Some data


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

Example three:
Copy the 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 CodeThe code is as follows:


$ 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
Copy the 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 is still automatically deleted after close

Output:
Copy the Code code as follows:


$ python tempfile_namedtemporaryfile.py

Temp: ', mode ' w+b ' at 0x1004481e0>

Temp.name:/VAR/FOLDERS/9R/9R1T+TR02RAXZK+F71Q50U+++UW/-TMP-/TMP0ZHZVX

Exists after Close:false

Tempfile.mkdtemp

Create a temporary directory, this is not much to say, look directly at the example:
Copy the 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 CodeThe code is as follows:


$ python tempfile_mkdtemp.py

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



Note: Directories need to be deleted manually.

Predicting Names

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

Instance:
Copy the 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 the Code code as follows:


$ python tempfile_namedtemporaryfile_args.py


Temp: ', 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 temporary file is saved according to the settings of the system environment variable Tmpdir, temp, or TMP The parameter text specifies whether the file is manipulated as text and, by default, False, indicating 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.

  • 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.