如何在Python中创建tmp文件?
我有引用文件路径的此函数:
some_obj.file_name(FILE_PATH)
其中FILE_PATH是文件路径的字符串,即 H:/path/FILE_NAME.ext
我想在python脚本中使用字符串内容创建文件FILE_NAME.ext:
some_string = 'this is some content'
怎么办呢?Python脚本将放置在Linux盒子中。
-
有一个用于python的
tempfile
模块,但是创建一个简单的文件也可以解决这个问题:new_file = open("path/to/FILE_NAME.ext", "w")
现在,您可以使用以下
write
方法对其进行写入:new_file.write('this is some content')
使用
tempfile
模块,它可能看起来像这样:import tempfile new_file, filename = tempfile.mkstemp() print(filename) os.write(new_file, "this is some content") os.close(new_file)
使用
mkstemp
完后,您有责任删除文件。使用其他参数,您可以影响文件的目录和名称。
更新
正如Emmet Speer正确指出的那样,使用时要考虑安全性
mkstemp
,因为客户端代码负责关闭/清理创建的文件。更好的方法是以下代码段(摘自链接):import os import tempfile fd, 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
不再需要时,调用删除文件。