1

我在 Python 3 中有当前代码:

import csv

if __name__ == '__main__':
    sp500_data = [
        {
            'company': 'GOOGLE',
            'headquarters': 'GOOGLEPLEX',
            'industry': 'ADS',
            'sector': 'TECH',
            'symbol': 'GOOG'
        },
        {
            'company': 'HEWLPA',
            'headquarters': 'WHATEVER',
            'industry': 'HARDWARE',
            'sector': 'TECH',
            'symbol': 'HP'
        }
    ]

    myfile = open("D:/test.csv", 'w', newline='')
    wr = csv.DictWriter(myfile, delimiter='\t', quoting=csv.QUOTE_ALL, fieldnames=sp500_data[0].keys)
    for sp500_company in sp500_data:
        wr.writerow(sp500_company)

但是,这会产生以下错误:

Traceback (most recent call last):
  File "D:\DEV\BlueTS\src\tsRetriever\dataRetriever\test.py", line 24, in <module>
    wr.writerow(sp500_company)
  File "C:\Python33\lib\csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Python33\lib\csv.py", line 146, in _dict_to_list
    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
  File "C:\Python33\lib\csv.py", line 146, in <listcomp>
    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
TypeError: argument of type 'builtin_function_or_method' is not iterable

我想了解我做错了什么,除此之外,我还想知道 Python 中存储最初以表格形式组织的基于列的数据的最佳方式是什么。

4

1 回答 1

4

您忘记调用.keys()方法:

wr = csv.DictWriter(myfile, delimiter='\t', quoting=csv.QUOTE_ALL,
                    fieldnames=sp500_data[0].keys())

注意()后面sp500_data[0].keys; .keys不是属性,是方法。

使用 acsv.DictWriter()是将字典格式的数据转换为 CSV 数据的绝佳方法。

于 2013-11-10T00:16:11.103 回答