A, tempfile Introduction
The module creates temporary files and directories. It applies to all supported platforms. TemporaryFile
, , NamedTemporaryFile
, TemporaryDirectory
And SpooledTemporaryFile
are high-level interface that provides automatic cleaning and can be used as context manager. mkstemp()
And mkdtemp()
the need to manually clean up low-level functions.
All functions and user-callable constructors have adopted other parameters that allow direct control of temporary files and directory location and name. This module uses the file name includes a string of random characters, it allows you to create these files safely in a shared temporary directory. To maintain backward compatibility, parameter order a little strange; for the sake of clarity, it is recommended to use keyword arguments.
Second, create a temporary file
1、TemporaryFile
The module defines the following user-callable items:
-
tempfile.
TemporaryFile
(mode ='w + b',buffering = None,encoding = None,newline = None,suffix = None,prefix = None,dir = None ) -
Returns a file-like object , it may be used as a temporary storage area. Use the same rules with which to create the file safely
mkstemp()
. It will be destroyed immediately after the closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is not created or deleted immediately after creating the file. Other platforms do not support this feature; your code should not rely on the use of temporary files created by this function, the file with or without a visible name in the file system.The resulting object may be used as context manager. After the completion of the file object context or destroyed, the temporary file is deleted from the file system.
The default mode parameter
'w+b'
file so created can be read and written is not closed. Binary mode, it behaves the same on all platforms, regardless of the stored data. Buffering, encoding, and is interpreted as line breaksopen()
.The directory, prefix and suffix parameters have the same meaning and default value
mkstemp()
.The returned object is true POSIX file object on the platform. On other platforms, it is a file-like object, whose
file
attributes are the real underlying file object.os.O_TMPFILE
If the flag is available and effective, the use of the mark (specific to Linux, the Linux kernel needs to version 3.11 or later).Version 3.5 has changed:
os.O_TMPFILE
now use this flag (if available).
Example:
from the tempfile Import TemporaryFile '' ' constructor TemporaryFile class, or return a file object. But the special place that the object of this document 1. File no corresponding file name of the program in addition to this program is not visible 2 is deleted while being closed '' ' the TEMP = TemporaryFile () # create a temporary file object temp.write ( ' Hello \ nworld ' ) # write to a temporary file # read the contents of the temporary file temp.seek (0) # re-read, and general files of different objects, the method can not perform seek less Print ( temp.read ()) temp.close () # close the file of deleted files
2、NamedTemporaryFile
-
tempfile.
NamedTemporaryFile
(mode ='w + b',buffering = None,encoding = None,newline = None,suffix = None,prefix = None,dir = None,delete = True ) -
NamedTemporaryFile run exactly the same way as TemporaryFile. Except that, when added NamedTemporaryFile delete parameters initialized, the default value is True. When this is fully consistent to True and TemporaryFile class. If it is False, then the temporary files are not deleted when the object is closed. It can be opened again by the same object in the following code. From
name
retrieve the class name attribute file object returned.
3、SpooledTemporaryFile
-
tempfile.
SpooledTemporaryFile
(max_size = 0,mode ='w + b',buffering = None,encoding = None,newline = None,suffix = None,prefix = None,dir = None ) -
Run this function is identical to this
TemporaryFile()
, but the spool data in memory until the file size exceeds max_size, or untilfileno()
until the method is called file, in which case the content will be written to disk, the operation continuesTemporaryFile()
.The resulting file has an additional method,
rollover()
the file regardless of their size will go to a disk file.The returned object is a file-like object, whose
_file
attributes are aio.BytesIO
orio.StringIO
objects (depending on whether the specified binary or text mode) or the real file object, depending on whetherrollover()
that has been called. File-like object canwith
use statements like normal files.Changes in version 3.3: truncate method now accepts a
size
parameter.
4、mkstemp
-
tempfile.
mkstemp
(suffix = None,prefix = None,dir = None,text = False ) -
mkstemp method is used to create a temporary file. This method is only used to create a temporary file , after calling tempfile.mkstemp function, it returns a tuple comprises two elements, the first element of the instructions of the security level of the temporary file, the second element indicating the path of the temporary file. Parameters suffix and prefix denote the suffix and prefix temporary file name; dir specifies the directory where temporary files are located, if not specified directory, to store temporary files. The system environment variables TMPDIR, TEMP or TMP setting; parameter text specifies whether to operate in the form of text files, the default is False, expressed as a binary file to operate.
Third, create a temporary directory
1 TemporaryDirectory
tempfile.
TemporaryDirectory
(suffix=None,prefix=None,dir =None)
This feature uses the same rules with which to create a temporary directory safely mkdtemp()
. The resulting object may be used as context manager. After the completion of context or destroy temporary directory object is deleted from the file system newly created temporary directory and all its contents.
From name
retrieving property returns the name of the directory object. When the object is returned as a context manager, name
will be as
in with
the assignment statement clause clause of the target to the target (if any).
By calling the cleanup()
explicitly clear the directory method.
New features in version 3.2.
2, mkdtemp
-
tempfile.
mkdtemp
(suffix=None,prefix=None,dir =None) -
As far as possible in the most secure way to create a temporary directory. Create a directory is no competition. The directory can only be read, write, and search by creating a user ID.
User
mkdtemp()
is responsible for deleting the temporary directory and its contents upon completion.The prefix, suffix and DIR parameters are the same
mkstemp()
.mkdtemp()
Returns the absolute pathname of the new directory.Changes in version 3.5: suffix, prefix and directories can now be provided in units of bytes for byte return value. Prior to this, only allow str. suffix and prefix now accepted and defaults to
None
using the appropriate default value.
3, gettempdir
-
tempfile.
gettempdir
() -
Used to return your temporary files folder path. This defines the default values for all parameters dir function of this module.
Python standard list of directories to search to find the calling user directory files can be created. The list is:
-
... directory named by the
TMPDIR
environment variable. -
... directory named by the
TEMP
environment variable. -
... directory named by the
TMP
environment variable. -
Platform-specific location:
-
In Windows, directories
C:\TEMP
,C:\TMP
,\TEMP
, and\TMP
in this order. -
In all other platforms, directories
/tmp
,/var/tmp
and/usr/tmp
in this order.
-
-
As a last resort, the current working directory.
Cache search results, please see
tempdir
the instructions below. -
4、gettempdirb
-
tempfile.
gettempdirb
() -
And
gettempdir()
yet the same, the return value in bytes.New in version 3.5.
5、gettempprefix
-
tempfile.
gettempprefix
() -
Return creating a temporary file name prefix. This does not include directory components.
6、gettempprefixb
-
tempfile.
gettempprefixb
() -
And
gettempprefix()
yet the same, the return value in bytes.New in version 3.5.
The module uses global variables to store temporary files for directory name returned gettempdir()
. It can be set directly to cover the selection process, but not encouraged to do so. All the functions in this module are used dir parameter, which can be used to specify the directory, which is the recommended method.
7、tempdir
-
tempfile.
tempdir
-
When set to other values
None
, the value of this variable dir defines the default parameters of the function defined in this module.If
tempdir
yesNone
(the default value) above any call function unlessgettempprefix()
the algorithm described according to initialize itgettempdir()
.
Fourth, example
The following are tempfile
some examples of typical usage of the modules:
Import the tempfile # 1. Create a temporary file and writes the number of data FP = tempfile.TemporaryFile () fp.write (B ' the Hello World! ' ) # 2. reads data from a file fp.seek (0) FP .read () # ! b'Hello world ' # 3. close the file, it will be deleted fp.close () # 4. create a temporary file with context manager with tempfile.TemporaryFile () AS fp: fp.write (b ' ! the Hello world ' ) fp.seek (0) fp.read () # ! b'Hello world ' # file is now closed and deleted # 6. use the context manager to create a temporary directory with tempfile () as tmpdirname.: Print ( ' the Created the Temporary Directory ' , tmpdirname) # catalog and content has been removed
Fifth, we do not recommend the use of functions and variables
Create a temporary file history is to first use the mktemp()
function to generate a file name, and then use this to create the file name. Unfortunately, this is not safe, because different processes may be mktemp()
the time between file creates a file with this name created in the first and subsequent attempts to process calls. The solution is to combine these two steps and creates the file immediately. The method consists of mkstemp()
using the other features.
-
tempfile.
mktemp
(suffix ='',prefix ='tmp',dir = None ) -
Starting with version 2.3 is not recommended:
mkstemp()
instead use.Absolute pathname does not exist when making the call to return the file. The prefix, suffix and DIR parameters similar to those
mkstemp()
, in addition to byte file name,suffix=None
andprefix=None
is not supported.caveat
Using this feature may introduce security vulnerabilities in the program. When you start using the filename it returns do anything else might beat you.
mktemp()
Usage can be easily replacedNamedTemporaryFile()
, passingdelete=False
parameters:>>> f = NamedTemporaryFile(delete=False) >>> f.name '/tmp/tmptjujjt' >>> f.write(b"Hello World!\n") 13 >>> f.close() >>> os.unlink(f.name) >>> os.path.exists(f.name) False