【问题标题】:Python Dictionary to csv file not workingPython字典到csv文件不起作用
【发布时间】:2017-11-28 18:20:28
【问题描述】:

抱歉,标题类型重复。我有一个问题发现和如何做到这一点的例子。我有一个从 Zendesk 提取的 json 文件。我正在做一个 json.dumps 来把它变成一个可读的格式和一个 python 字典。我在 for 循环中有以下内容,因此我可以从 json 文件中获取所需的信息并将其写入 csv 文件。

for item in data['results']:
    print(
        item['id'] ,item['via']['channel'], item['via']['source']['from'], item['subject'], item['tags'],
        item['created_at'], item['status'], item['custom_fields'][12], item['custom_fields'][12]['value'],
        item['result_type'], item['priority']

从这段代码中,我得到了我想要的带有正确信息的项目。

我尝试了以下方法将其打印到文件中,但我在文件中返回的只是最后一条记录

import csv

with open('file.txt', 'w') as file:

csv_app = csv.writer(file)
for item in python_data['results']:
    csv_app.writerows(item['id'], item['via']['channel'],item['via']['source']['from'],item['subject'], item['tags'],
           item['created_at'], item['status'], item['custom_fields'][12], item['custom_fields'][12]['value'],
           item['priority'], item['result_type'])

我想获得一些关于如何获得所有东西的建议(我已经尝试了很多东西)还有一个 item['via']['source']['from']['name '] 我已经取出,因为它在没有价值时会导致错误。我假设一个 if 条件,如何逐个字段处理这个问题。

任何帮助或指出我正确的方向将不胜感激。

提前致谢。

【问题讨论】:

  • 如果你多次打开写入数据,那么你应该使用a而不是wappend模式打开
  • 当您使用writerow 而不是writerows 时会发生什么?

标签: python json csv dictionary zendesk-api


【解决方案1】:

首先,file 是 python 中的保留字。使用其他名称,例如 ffout

其次,使用writerow 而不是writerows

第三,在你的例子中你的缩进是关闭的(最后五行应该缩进一级)。

import csv

data = {'results': [{'A': 1, 'B': 2, 'C': 3}, 
                    {'A': 10, 'B': 20, 'C': 30}]}
with open('test.txt', 'w') as f:
    csv_app = csv.writer(f)
    for item in data['results']:
        csv_app.writerow([item[x] for x in ['A', 'B', 'C']])

$ cat test.txt
1,2,3
10,20,30

【讨论】:

  • 完美你 Alexander,我发誓我已经尝试过同样的事情,但最后一行是关键,我现在能够得到我需要的东西。非常感谢您的帮助。
  • 几乎成功了,我有一个描述字段可能会变得很大并且不知道是什么原因导致它但是得到一个 unicodeEncodeError 'charmap' 编解码器无法在位置 799 编码字符 '\u2502' : 字符映射到
  • 也许这会有所帮助:stackoverflow.com/questions/27092833/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 2014-11-17
相关资源
最近更新 更多