将python json转换为CSV [英] Python json to CSV
问题描述
我正在尝试将json数据集文件转换为csv.我对python真的很陌生,并且一直在论坛上寻找并且似乎无法解决我的问题.我在下面附加了json数据url链接以及我的代码.预先感谢!
I am trying to convert a json data set file into csv. I am really new to python, and have been looking on the forums and cannot seem to resolve my issues. I have attached the json data url link in below along with my code. Thanks in advance!
https://data.ny.gov /api/views/nqur-w4p7/rows.json?accessType=DOWNLOAD
import json
import csv
inputFile = ("rows.json?accessType=DOWNLOAD", "r")
data = json.load(inputFile)
with open("Data.csv","wb") as csvfile:
csv_writer = csv.DictWriter(csvfile,delimiter=",", fieldnames=["data", "new_york_state_average_gal", "albany_average_gal", "binghamton_average_gal", "bu\
ffalo_average_gal", "nassau_average_gal", "new_york_city_average_gal", "rochester_average_gal", "utica_average_gal"])
csv_writer.writerheader()
csv_writer.writerows(data)
这是我遇到的错误:
File "ChangeDataType.py", line 5, in <module>
data = json.load(inputFile)
File "/usr/lib64/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'tuple' object has no attribute 'read'
推荐答案
发生错误是因为您创建了一个元组:
Your error happens because you made a tuple:
inputFile = ("rows.json?accessType=DOWNLOAD", "r")
并且您正在尝试在该元组中使用json.load
.由于json.load
仅适用于文件,因此您需要调用open
函数:
And you're trying to use json.load
in that tuple. Since json.load
works only on files, you need to call the open
function:
inputFile = open("rows.json?accessType=DOWNLOAD", "r")
"r"
部分表示您正在打开文件进行读取.
The "r"
part indicates you're opening the file for reading.
这篇关于将python json转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!