具有自定义名称的临时文件/目录? [英] temp files/directories with custom names?

查看:47
本文介绍了具有自定义名称的临时文件/目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中使用用户定义的名称创建临时文件/目录.我知道 tempfile .但是我看不到任何以文件名作为参数的函数.

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.

注意:我需要这个来对包含临时文件的临时目录上的 glob(文件名模式匹配)功能进行单元测试,而不是使用实际的文件系统.

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.

推荐答案

您可以将 open() 与您需要的任何文件名一起使用.

You can use open() with whatever file name you need.

例如

open(name, 'w')

打开

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)

或者您可以使用 mkdtemp 创建一个临时目录,然后使用 open 在临时目录中创建一个文件.

Or you can create a temp directory using mkdtemp and then use open to create a file in the temporary directory.

这篇关于具有自定义名称的临时文件/目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆