简体   繁体   中英

Python Dictionary to csv file not working

Sorry for the duplicate title type. I am having a problem finding and example on how to accomplish this. I have a json file I'm pulling from Zendesk. I'm doing a json.dumps to get that to a readable formation and in a python dictionary. I have the following in a for loop so I can get just the info I need out of the json file and write it to a csv file.

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']

from this code I get the items I want with the correct information.

I have tried the following to print this out to a file but all I get returned in the file is the last record

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'])

I would like to get some suggestions on how to get everything (i've tried alot of stuff) Also there is an item['via']['source']['from']['name'] I have taken out due to it causing errors when there is no value there. How do I handle this on a field by field basis I'm assuming a if condition.

Any help or pointing me in the right direction would be greatly appreciated.

Thanks in advance.

First, file is a reserved word in python. Use something else such as f or fout .

Second, use writerow instead of writerows .

Third, your indentation is off in your example (last five lines should be indented one level).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM