在Python中生成临时文件名而不实际创建文件
关于如何在Python中生成随机文件名的最佳方法的回答,展示了如何在Python中创建临时文件。
在我的情况下,我只需要一个临时文件名。
调用 tempfile.NamedTemporaryFile()
会在实际创建文件后返回一个文件句柄。
有没有办法只获取文件名呢?我试过这个:
# Trying to get temp file path
tf = tempfile.NamedTemporaryFile()
temp_file_name = tf.name
tf.close()
# Here is my real purpose to get the temp_file_name
f = gzip.open(temp_file_name ,'wb')
...
9 个回答
9
可能有点晚了,但这个有什么问题吗?
import tempfile
with tempfile.NamedTemporaryFile(dir='/tmp', delete=False) as tmpfile:
temp_file_name = tmpfile.name
f = gzip.open(temp_file_name ,'wb')
10
我们尽量不要想得太复杂:
import os, uuid, tempfile as tf
def make_temp_name(dir = tf.gettempdir()):
return os.path.join(dir, str(uuid.uuid1()))
13
tempfile.mktemp()
这个函数可以做到这一点。
不过要注意,这个函数已经不推荐使用了。它不会真的创建文件,而且它是tempfile库中的一个公共函数,这和使用_get_candidate_names()
不一样。
之所以不推荐使用这个函数,是因为在你调用它和真正尝试创建文件之间可能会有时间差。不过在我的情况下,这种情况发生的可能性非常小,即使失败了也能接受。但最终还是要看你自己的使用场景来决定。
97
如果你只想要一个临时文件的名字,可以使用里面的一个临时文件函数 _get_candidate_names()
:
import tempfile
temp_name = next(tempfile._get_candidate_names())
% e.g. px9cp65s
再调用一次 next
,会返回另一个名字,依此类推。这并不会给你临时文件夹的路径。如果你想要默认的 'tmp' 目录,可以使用:
defult_tmp_dir = tempfile._get_default_tempdir()
% results in: /tmp
108
我觉得最简单、最安全的方法是这样的:
path = os.path.join(tempfile.mkdtemp(), 'something')
会创建一个临时目录,只有你自己可以访问,所以不会有安全问题。不过,这个目录里不会生成任何文件,所以你可以随意选择一个文件名来在这个目录里创建。记得最后还是要删除这个文件夹。
补充一下:在Python 3中,你可以使用 tempfile.TemporaryDirectory()
作为上下文管理器,这样就可以自动帮你处理删除的事情:
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'something')
# use path