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

Posted

技术标签:

【中文标题】ValueError:无效的文件路径或缓冲区对象类型:<class \'dict\'> python【英文标题】: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 的上述评论为我解决了这个问题。 【参考方案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 

【讨论】:

以上是关于ValueError:无效的文件路径或缓冲区对象类型:<class 'dict'> python的主要内容,如果未能解决你的问题,请参考以下文章

ValueError:缓冲区 dtype 不匹配,预期为“Python 对象”但得到“双倍”

Cordova:无效数据,块必须是字符串或缓冲区,而不是对象

无效数据,块必须是字符串或缓冲区,而不是对象 - 离子和火力

从零开始的Java开发1-6-4 Java输入输出流:File类绝对路径和相对路径字节流缓冲流字符流对象序列化

ValueError:np.nan 是无效文档、预期字节或 unicode 字符串

scikit-learn 中的 TfidfVectorizer:ValueError:np.nan 是无效文档