如何在Python中创建tmp文件?

如何在Python中创建tmp文件?,第1张

如何在Python中创建tmp文件

有一个用于python的

tempfile
模块,但是创建一个简单的文件也可以解决这个问题:

new_file = open("path/to/FILE_NAME.ext", "w")

现在,您可以使用以下

write
方法对其进行写入:

new_file.write('this is some content')

使用

tempfile
模块,它可能看起来像这样:

import tempfilenew_file, filename = tempfile.mkstemp()print(filename)os.write(new_file, "this is some content")os.close(new_file)

使用

mkstemp
完后,您有责任删除文件。使用其他参数,您可以影响文件的目录和名称。


更新

正如Emmet Speer正确指出的那样,使用时要考虑安全性

mkstemp
,因为客户端代码负责关闭/清理创建的文件。更好的方法是以下代码段(摘自链接):

import osimport tempfilefd, path = tempfile.mkstemp()try:    with os.fdopen(fd, 'w') as tmp:        # do stuff with temp file        tmp.write('stuff')finally:    os.remove(path)

os.fdopen
文件描述符包装在Python文件对象中,该文件对象会在
with
退出时自动关闭。
os.remove
不再需要时,调用删除文件。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5644358.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存