Abstract: Temporary files are often used to hold data that cannot be kept in memory, or to pass to external programs that must be read from the file. We normally generate a unique file name in the/TMP directory, but creating temporary files safely is not that simple and requires many rules.
This article is written by Kang Xiaoyong and published by Huawei Cloud Community.
1, the preface
Temporary files are often used to hold data that cannot be kept in memory, or to pass to external programs that must be read from the file. We normally generate a unique file name in the/TMP directory, but creating temporary files safely is not that simple and requires many rules. Never try to do this yourself. Instead, use library functions to do it. And clean up temporary files carefully, too.
The biggest problem with temporary files is the ability to predict the filename, which allows malicious users to create soft links to hijack temporary files.
2. Introduction to tempFile module
The common module for creating temporary files is tempFile. The library functions for creating temporary files include:
Tempfile.mktemp # Unsafe and prohibited
Mkstemp # create TMP files randomly, default created file in/TMP directory, of course can be specified.
TemporaryFile # Create files in memory, files will not be stored on disk, delete immediately after closing (can be used)
Tempfile as expected. NamedTemporaryFile (delete = True) when the delete = True role similar to the above, when it is False, will be stored in the disk (use)
3. Introduction of examples
The following describes the safe and unsafe ways to create temporary files.
3.1 Incorrect Examples:
False 1:
import osimport tempfile# This will most certainly put you at risktmp = os.path.join(tempfile.gettempdir(), filename)if not os.path.exists(tmp): with open(tmp, "w") file: file.write("defaults")
Copy the code
False 2:
import osimport tempfileopen(tempfile.mktemp(), "w")
Copy the code
False 3:
filename = "{}/{}.tmp".format(tempfile.gettempdir(), os.getpid())open(filename, "w")
Copy the code
3.2 Correct Examples
The correct one:
fd, path = tempfile.mkstemp()try: with os.fdopen(fd, 'w') as tmp: # do stuff with temp file tmp.write('stuff')finally: os.remove(path)
Copy the code
The correct 2:
TemporaryFile() as TMP: # Do stuff with TMP tmp.write('stuff')Copy the code
The correct 3:
TMP = tempfile as expected. NamedTemporaryFile (delete = True) try: # do stuff with temp TMP. Write (' stuff ') finally: TMP. The close () # file closed or deletedCopy the code
Click to follow, the first time to learn about Huawei cloud fresh technology ~