gpt4 book ai didi

python - 使用 Python 3 创建具有唯一名称的临时文件?

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:52 26 4
gpt4 key购买 nike

我想创建一个具有特定名称的临时文件(如果可能的话,使用特定的扩展名)。

例子:

-mytempfile.txt
-mytempfile2.xml

我一直在阅读有关临时文件库的信息,但据我所知我只能设置以下参数

(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

最佳答案

做你要求的最安全的方法是,正如 Dan 指出的那样,不需要为文件指定任何名称,我只使用 OP 在问题中要求的后缀和前缀。

import os
import tempfile as tfile
fd, path = tfile.mkstemp(suffix=".txt",prefix="abc") #can use anything
try:
with os.fdopen(fd, 'w') as tmpo:
# do stuff with temp file
tmpo.write('something here')
finally:
os.remove(path)

要了解有关与此相关的安全方面的更多信息,您可以引用此 link

好吧,如果您不能使用操作系统并且需要执行这些操作,那么请考虑使用以下代码。

import tempfile as tfile
temp_file=tfile.NamedTemporaryFile(mode="w",suffix=".xml",prefix="myname")
a=temp_file.name

temp_file.write("12")
temp_file.close()

a 将为您提供文件的完整路径,例如:

'/tmp/mynamesomething.xml'

如果你最后不想删除文件,那么使用:

temp_file=tfile.NamedTemporaryFile(delete=False) #along with other parameters of course.

关于python - 使用 Python 3 创建具有唯一名称的临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51775775/

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