问题
How to create a temporary files/directories with user defined names in python. I am aware of tempfile . However I couldn't see any function with filename as argument.
Note: I need this for unit testing the glob(file name pattern matching) functionality on a temporary directory containing temporary files rather than using the actual file system.
回答1:
You can use open()
with whatever file name you need.
e.g.
open(name, 'w')
Open
Or
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()
# Clean up the temporary file yourself
os.remove(filename)
Or you can create a temp directory using mkdtemp
and then use open
to create a file in the temporary directory.
来源:https://stackoverflow.com/questions/39592524/temp-files-directories-with-custom-names