使用命名临时文件

use*_*827 3 python temporary-files

with NamedTemporaryFile(suffix='.shp').name as tmp_shp:
    df.to_file(tmp_shp)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我收到此错误:

with NamedTemporaryFile(suffix='.shp').name as tmp_shp:
    df.to_file(tmp_shp)
Run Code Online (Sandbox Code Playgroud)

如何使用 with 语句使用命名临时文件?既然tmp_shp只是一条路径,它在 之外仍然可用吗with

Sha*_*ger 5

name属性是一个字符串;尝试在语句中访问它with使其成为托管资源(并且str没有上下文管理的概念)。您需要管理其本身,并根据需要NamedTemporaryFile访问:name

with NamedTemporaryFile(suffix='.shp') as tmp_shp:
    df.to_file(tmp_shp.name)  # Access .name here, assuming you need a str
Run Code Online (Sandbox Code Playgroud)

如果to_file接受类似文件的对象(我找不到这种方法的文档),那么您将.name完全避免使用(在任一行中)。

更新:因为你在 Windows 上,所以在关闭之前你实际上无法打开由NamedTemporaryFilewith delete=True(默认)NamedTemporaryFile打开的文件(这意味着你不能使用写入该文件句柄的任何数据,因为它已被删除,并引入即使仅使用它来生成唯一名称,也会出现竞争条件;此时文件将被删除,因此您实际上只是创建一个新文件,但其他人可能会在稍后与您竞争创建该文件)。我在这里可以建议的最好方法是在不支持删除的情况下使用它来获得唯一的名称,将其包装起来以强制删除,例如:

tmp_shp = None
try:
    with NamedTemporaryFile(suffix='.shp', delete=False) as tmp_shp:

        df.to_file(tmp_shp.name)  # Access .name here, assuming you need a str

        ... do any other stuff with the file ...
finally:
    if tmp_shp is not None:
        os.remove(tmp_shp.name)
Run Code Online (Sandbox Code Playgroud)

是的,它很丑。这里没有很多好的选择;NamedTemporaryFile在 Windows 上从根本上被破坏了。