1

我得到了一些数据,我需要将其转换为 csv 文件。我不是编码员,但我认为 python 可以帮助我处理这些字典/元组。

a = {
 'page': '1',
 'records': 984,
 'rows': [{'cell': ['2012000000885',
                    'A. B. OLIVEIRA - ME',
                    '10\\/08\\/2012',
                    '2.200,00',
                    '0,00',
                    '0,00'],
           'id': '2012000000885;02070712000102;2012;4'},
          {'cell': ['2012000000440',
                    'A. C SILVA E CIA LTDA',
                    '26\\/04\\/2012',
                    '600,00',
                    '600,00',
                    '600,00'],
           'id': '2012000000440;02070712000102;2012;4'},
          {'cell': ['2012000000104',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '27\\/01\\/2012',
                    '100,00',
                    '100,00',
                    '100,00'],
           'id': '2012000000104;02070712000102;2012;4'},
          {'cell': ['2012000000261',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '01\\/03\\/2012',
                    '200,00',
                    '200,00',
                    '200,00'],
           'id': '2012000000261;02070712000102;2012;4'},
          {'cell': ['2012000000360',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '28\\/03\\/2012',
                    '200,00',
                    '200,00',
                    '200,00'],
           'id': '2012000000360;02070712000102;2012;4'}],
 'total': 1}   

我只对“行”感兴趣,我需要单独的“Id”和“单元格”将它们导入 csv 文件。预先感谢您的任何帮助。

罗杰里奥·马里尼奥

4

2 回答 2

4
import csv
with open('output.csv', 'wb') as fout:
    csvout = csv.writer(fout)
    for row in a['rows']:
        csvout.writerow( [row['id']] + row['cell'] )

创建一个 CSV 文件,其中第一列作为 ID,后续列作为任何单元格。

于 2012-10-20T14:51:37.443 回答
0

这更清洁:

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
于 2015-02-13T22:56:04.317 回答