temp files/directories with custom names?

限于喜欢 提交于 2020-01-24 19:53:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!