
有一个用于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不再需要时,调用删除文件。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)