2017-03-04 4 views
2

ファイル名が必要な関数のURLを使用する一般的なレシピを探しています。私は困惑しましたが、少し複雑で間違っているのは簡単です。Pythonでファイル名を要求する関数へのURLの提供方法

この場合、私の機能はread_fileからgeopandasまでですが、いずれの場合も同じ問題になります。働き、そしてあまりにもひどい見えませんが、多少の変形が原因一時ファイルの寿命に、OSError: no such file or directoryを上げるので、私は、それを見つけるために束を実験していた

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) 

。私は永続的なファイルでファイルシステムを混乱させたくありません。

これは失敗します。

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) 

は、より明白な思い出に残る、または防弾方法はありますか?そうでなければあなたは必ずそれが適切に自分自身をクリーンアップするために必要があるでしょうwith NamedTemporaryFile() as tfileだけのPython 3で動作します:

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 

注:

+0

あなたは[ 'contextlib.contextmanager'](https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager)使用することができ、と 'ウィットhである。申し訳ありませんより良い答えを提供する時間。 –

答えて

2

あなたは、一時ファイルの寿命を管理するためのコンテキストマネージャを使用することができますPythonの2

使用法のために:

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

それは、ありがとう!実際、 'tfile.flush()'もなくても動作するようです。 –

+1

バイト数が少なすぎると、バッファがフラッシュされない可能性があり、geopandasはファイルから空のデータまたは部分データを読み取ろうとします。 'requests.get(url).content'を' 'hello''に置き換え、' gpd.read_file'がどんなものかを見てください。 –

関連する問題