Python 字典到 csv 文件不工作
Python Dictionary to csv file not working
抱歉,标题类型重复。我在查找问题和如何完成此操作的示例时遇到问题。我有一个从 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 条件,我该如何逐个字段处理这个问题。
任何帮助或为我指明正确的方向将不胜感激。
提前致谢。
首先,file
是python中的保留字。使用其他内容,例如 f
或 fout
.
其次,使用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
抱歉,标题类型重复。我在查找问题和如何完成此操作的示例时遇到问题。我有一个从 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 条件,我该如何逐个字段处理这个问题。
任何帮助或为我指明正确的方向将不胜感激。
提前致谢。
首先,file
是python中的保留字。使用其他内容,例如 f
或 fout
.
其次,使用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