[英]Json file to csv in Python
如果我使用此腳本在Python中將Json轉換為Csv:
import json
import csv
with open("data.json") as file:
data = json.loads(file)
with open("data.csv", "w") as file:
csv_file = csv.writer(file)
for item in data:
csv_file.writerow([item['studio'], item['title']] + item['release_dates'].values())
它將引發錯誤消息:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
當您應該使用json.loads()
時,您正在使用json.load()
。
json.loads
用於讀取字符串,而json.load
用於讀取文件。
請訪問此處以獲取更多信息: https : //docs.python.org/2/library/json.html 。
另外,它們不相關,但是可以with
語句鏈接。
with open("data.json") as json_file, open("data.csv", "w") as csv_file:
csv_file = csv.writer(csv_file)
for item in json.load(json_file):
csv_file.writerow(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.