Skip to main content
 首页 » 编程设计

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

2024年10月01日7mq0036

我正在寻找将 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)