如何提供 URL 以在 Python 中需要文件名的函数

How to supply URL to function requiring a filename in Python

我正在寻找将 URL 用于需要文件名的函数的通用方法。我已经猜出来了,但是有点复杂,容易出错。

在这种情况下,我的函数是 geopandas 中的 read_file,但无论如何都会出现同样的问题。

import tempfile, requests
import geopandas as gpd

def as_file(url):
    tfile = tempfile.NamedTemporaryFile()
    tfile.write(requests.get(url).content)
    return tfile

URL = 'https://raw.githubusercontent.com/bowmanmc/ohiorepresents/master/data/congressional.min.json'
tf = as_file(URL)
gpd.read_file(tf.name)

这行得通,而且看起来不太糟糕,但我不得不进行大量试验才能找到它,因为由于临时文件的生命周期,轻微的变体会增加 OSError: no such file or directory;但我也不想用永久文件弄乱文件系统。

这失败了:

def as_file(url):
    tfile = tempfile.NamedTemporaryFile()
    tfile.write(requests.get(url).content)
    return tfile.name

gpd.read_file(as_file(URL))

甚至这个:

def as_file(url):
    tfile = tempfile.NamedTemporaryFile()
    tfile.write(requests.get(url).content)
    return tfile

gpd.read_file(as_file(URL).name)

是否有更明显、更难忘或更可靠的方法?

您可以使用上下文管理器来管理临时文件的生命周期:

from contextlib import contextmanager

@contextmanager
def as_file(url):
    with tempfile.NamedTemporaryFile() as tfile:
        tfile.write(requests.get(url).content)
        tfile.flush()
        yield tfile.name

注意:with NamedTemporaryFile() as tfile 仅适用于 Python 3。否则,您必须确保自己为 Python 2.

正确清理

用法:

with as_file(URL) as filename:
    gpd.read_file(filename)