【问题标题】:ValueError: Invalid file path or buffer object type: <class 'dict'> pythonValueError:无效的文件路径或缓冲区对象类型:<class 'dict'> python
【发布时间】:2020-05-28 04:02:59
【问题描述】:

运行以下代码时出现以下错误:

ValueError:无效的文件路径或缓冲区对象类型:类'dict'>

代码:

import requests as rq
import pandas as pd
import json

df = pd.DataFrame()
temp = pd.DataFrame()
with open("tfl_list_stops.txt", encoding="utf-8") as file:
    fileList = [line.strip() for line in file]
for ids in fileList:
    r = rq.get('https://api.tfl.gov.uk/StopPoint/' + ids + '?includeCrowdingData=true')
    r = r.text
    content = json.loads(r)
    temp = pd.read_json(content)
    df = pd.concat([df, temp], axis=1)
df.to_csv('stop_loc.csv')

【问题讨论】:

  • 我的猜测:删除content = json.loads(r)并将下一行更改为temp = pd.read_json(r)。
  • @Flux 的上述评论为我解决了这个问题。

标签: python json pandas dataframe python-requests


【解决方案1】:

你可以试试这个,

import requests as rq
import pandas as pd
import json

dfs = []

with open('tfl_list_stops.txt', encoding='utf-8') as file:
    file_list = [line.strip() for line in file]

for ids in file_list:
    url = 'https://api.tfl.gov.uk/StopPoint/' + ids + '?includeCrowdingData=true'
    r = rq.get(url)

    content = json.loads(r.text)
    dfs.append(pd.DataFrame([content]))

df = pd.concat(dfs, ignore_index=True, sort=False)
df.to_csv('stop_loc.csv')

print(df)

                                               $type     naptanId  \
0  Tfl.Api.Presentation.Entities.StopPoint, Tfl.A...  940GZZLUBMY   

         modes  icsCode smsCode            stopType stationNaptan  \
0  [bus, tube]  1000021   77031  NaptanMetroStation   940GZZLUBMY   

                                               lines  \
0  [{'$type': 'Tfl.Api.Presentation.Entities.Iden...   

                                           lineGroup  \
0  [{'$type': 'Tfl.Api.Presentation.Entities.Line...   

                                      lineModeGroups  status           id  \
0  [{'$type': 'Tfl.Api.Presentation.Entities.Line...    True  940GZZLUBMY   

                       commonName  placeType  \
0  Bermondsey Underground Station  StopPoint   

                                additionalProperties  \
0  [{'$type': 'Tfl.Api.Presentation.Entities.Addi...   

                                            children       lat       lon  
0  [{'$type': 'Tfl.Api.Presentation.Entities.Stop...  51.49775 -0.063993 

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2018-09-03
    • 2021-08-06
    • 2021-04-14
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2019-03-29
    相关资源
    最近更新 更多