Python tempfile module learning notes (temporary files)

Source: Internet
Author: User

Tempfile. TemporaryFile

It is best to use the TemporaryFile function to create a temporary file if your application needs a temporary file to store data, but it does not need to be shared with other programs. Other applications cannot find or open the file because it does not reference the file system table. Temporary files created using this function are automatically deleted after they are closed.

Instance 1:
Copy codeThe Code is as follows:
Import OS
Import tempfile

Print 'Building a file name yourself :'
Filename = '/tmp/guess_my_name.20.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 method for creating a common file and TemporaryFile (). Note: The file created with TemporaryFile () has no file name.

Output:
Copy codeThe Code is 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, you can use the w + B permission to create a file. This applies to any platform, and the program can read and write it. This example illustrates the difference between the method for creating a common file and TemporaryFile (). Note: The file created with TemporaryFile () has no file name.


Copy codeThe Code is 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, you can use the w + B permission to create a file. This applies to any platform, and the program can read and write it.

Example 2:
Copy codeThe Code is as follows:
Import OS
Import tempfile

Temp = tempfile. TemporaryFile ()
Try:
Temp. write ('some data ')
Temp. seek (0)

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

You must use seek () to write data.

Output:
Copy codeThe Code is as follows:

$ Python tempfile_TemporaryFile_binary.py

Some data
If you want to run the file in text mode, you must change the mode to 'W + t' when creating the file '.

Example 3:
Copy codeThe Code is 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, creating a file with a name is the easiest way. This is what NamedTemporaryFile needs to do. You can use the name attribute to access its name.
Copy codeThe Code is 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 automatically deleted after close

Output:
Copy codeThe Code is 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

Create a temporary directory. For more information, see the example below:
Copy codeThe Code is 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: You must manually delete the directory.

Predicting Names

Use three parameters to control the file name. The formula for generating the name is dir + prefix + random + suffix.

Instance:
Copy codeThe Code is 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 codeThe Code is 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 only used to create temporary files and call tempfile. after the mkstemp function is used, the system returns the tuples containing two elements. The first element indicates the security level of the temporary file, and the second element indicates the path of the temporary file. The suffix and prefix parameters indicate the suffix and prefix of the temporary file name. The dir specifies the directory where the temporary file is located. If no directory is specified, the system environment variable TMPDIR, set TEMP or TMP to save the temporary file. The text parameter specifies whether to operate the file in the form of text. The default value is False, indicating that the file is operated in binary format.

Tempfile. mktemp ([suffix = ''[, prefix = 'tmp '[, dir = None])

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

Tempfile. tempdir

This attribute is used to specify the default folder where the temporary file (folder) is created. If this attribute is not set or set to None, Python returns the following environment variables TMPDIR, TEMP, TEMP specified directory. 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 for saving the temporary file.

 

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.