gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:37:50 28 4
gpt4 key购买 nike

回答 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com