如何用 Python 创建 tmp 文件?

我有这样一个函数,它引用一个文件的路径:

some_obj.file_name(FILE_PATH)

其中 FILE _ PATH 是文件路径的字符串,即 H:/path/FILE_NAME.ext

I want to create a file FILE_NAME.ext inside my python script with the content of a string:

some_string = 'this is some content'

How to go about this? The Python script will be placed inside a Linux box.

161049 次浏览

There is a tempfile模块 for python, but a simple file creation also does the trick:

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的调用会删除该文件。

我想你要找的是 tempfile.NamedTemporaryFile

import tempfile
with tempfile.NamedTemporaryFile() as tmp:
print(tmp.name)
tmp.write(...)

But:

在命名的临时文件仍然打开的情况下,是否可以使用该名称再次打开该文件,这在不同的平台上有所不同(它可以在 Unix 上使用,但不能在 Windows NT 或更高版本上使用)。

如果你担心这个问题:

import os, tempfile
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
print(tmp.name)
tmp.write(...)
finally:
tmp.close()
os.unlink(tmp.name)