簡體   English   中英

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中的保留字。 使用其他東西,例如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM