如果我使用这个脚本在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
答案 0 :(得分:1)
当您使用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(...)