【问题标题】:Json file to csv in Python在 Python 中将 Json 文件转换为 csv
【发布时间】:2015-10-25 10:13:35
【问题描述】:

如果我使用此脚本在 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

【问题讨论】:

  • 尝试data = json.load(file) 而不是data = json.loads(file)loads 用于字符串。

标签: python json csv


【解决方案1】:

当你应该使用json.load()时,你正在使用json.loads()

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(...)

【讨论】:

  • 回溯(最近一次调用最后一次):文件“”,第 1 行,在 IOError:[Errno 2] 没有这样的文件或目录:'data.json' 我明白了如果我进行更改,则会出错。
  • 该错误似乎发生在open() 行,而不是json.load 行。
  • 找不到文件的位置。我已将文件保存在程序文件内的 python 文件夹中。仍然无法访问。不知道为什么会这样。
  • Traceback(最近一次调用最后):文件“”,第 3 行,在 文件“C:\Users\dell\AppData\Local\Programs\Python\Python27\lib \json_init_.py",第 268 行,在加载 parse_constant=parse_constant,object_pairs_hook=object_pairs_hook, **kw) 文件"C:\Users\dell\AppData\Local\Programs\Python\Python27\ lib\json_init_.py”,第 319 行,在负载中返回 _default_decoder.decode(s) 文件“C:\Users\dell\AppData\Local\Programs\Python\Python27\lib\json\ decoder.py",第 342 行,在 decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2065)
猜你喜欢
  • 2015-01-13
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2017-11-30
  • 2018-03-06
  • 2019-08-15
  • 1970-01-01
  • 2018-07-14
相关资源
最近更新 更多