在python中用csv中的头文件存储数据

时间:2017-04-02 20:34:45

标签: python csv

我正在尝试将一些数据存储在csv文件中。我能够存储数据,但看起来像这样

1901,1909,1911,1913,1917
5,5,5,4,6

第一行是年名,第二行是值。 我的代码如下

import os
import csv
from collections import Counter
from csv import reader


def read_data(filename):
    year = 3
    with open(filename) as f:
        next(f, None)  # discard header
        year2rel = Counter(int(line[YEAR]) for line in reader(f))
        return year2rel

file_exists = os.path.isfile('mycsvfile.csv')
def store_data(value):
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as f:
        w = csv.DictWriter(f, my_dict.keys())
        if not file_exists:
            w.writeheader()
        print 'w: ', w
        w.writerow(my_dict)

if __name__ == '__main__':
    filename = '/home/rob/songs_detail.csv'
    a = read_songs(filename)
    b = store_data(a)

但我想要包含标题,使其看起来像

year values
1901 5
1909 5
1911 5
1913 4
1917 6        

我试图更改我的代码,但它对我不起作用。我尝试了类似下面但不成功的事情。感谢任何提示或帮助。

def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as csvfile:  
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()  # file doesn't exist yet, write a header

        writer.writerow({'year': my_dict[0], 'values': my_dict[1]})

这给我以下错误。

'ValueError: dict contains fields not in fieldnames: 'values', 'year'

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,代码如下,可能对某人有帮助。

def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    print 'type of: ', type(my_dict)
    with open('mycsvfile.csv', 'wb') as csvfile:
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()
        for k, v in my_dict.items():
            print(k, v)
            writer.writerow({'year': k, 'values': v})

实际上我缺少以正确的方式添加循环,因此它总是在没有标题的csv文件中产生。现在它根据我的要求完美地工作。