python - 生成临时文件名而不在 Python 中创建实际文件

标签 python temporary-files

回答 Best way to generate random file names in 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')
...

最佳答案

如果你只想要一个临时文件名,你可以调用内部临时文件函数_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 

关于python - 生成临时文件名而不在 Python 中创建实际文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541416/

相关文章:

python - 欧拉-拉格朗日的 Sympy 隐式微分

ruby-on-rails - 在 Rails 中将临时文件附加到电子邮件时出错

java - 使用 java.nio.file.Files.createTempDirectory 时出现 NoSuchFileException

java - 从文本文件中删除多行

python - Statsmodels 抛出 "overflow in exp"和 "divide by zero in log"警告,伪 R 平方是 -inf

python - 最快/最有效的文本和 float 数据存储格式

c++ - Boost python参数错误

python - 尝试使用多个空列(NaN)取消堆叠数据帧

Python 临时文件模块和线程运行不佳;我究竟做错了什么?

ruby-on-rails - rails3,对使用 params[ :filename]. tempfile.path 与 params[ :filename][:tempfile]. path 感到困惑