缺少使用python编写csv文件的值

时间:2014-03-08 23:08:38

标签: python csv dictionary

我正在尝试用dthonnary编写一个带有python的csv文件,如下所示:

1: [(3456,12),(4521,78)]
2: [(5478,45),(5609,43)]
3: [(8756,34),(6721,90)]
等等......

我有几本这样的词典。它们可以有30个键。要在csv文件中编写所有字典,我编写了以下代码,这些代码将应用于每个字典:

for i,j in dictionnary.iteritems():
   for k in j:
     cr=csv.reader(open('/home/file.csv','rb'))
     datalist=list(cr)
     c=writerows(datalist+[[self.user_id, i,k[0],k[1]])

当我打开csv文件时,只写了一部分字典。当我多次运行代码时,不会丢失相同的字典条目。 我不明白会发生什么。问题可能来自哪里?

2 个答案:

答案 0 :(得分:0)

每次写信时都会读取文件。这意味着,您需要两次读取数据。正如其他人所建议的那样,将csv.reader( open(...) )部分排除在外。此外,我认为您正在尝试追加数据到CSV的末尾。如果这就是你所追求的,请尝试在with(追加二进制)模式下使用ab命令和opening the file

with open('/home/file.csv','ab') as csvfile:
    csvwriter = csv.writer( csvfile, delimiter=' ', quoting=csv.QUOTE_MINIMAL )
    for i,j in dictionary.iteritems():
        for k in j:
            csvwriter.writerow( [ self.user_id, i, k[0], k[1] ] )

答案 1 :(得分:0)

也许这段代码会为您提供有关如何管理完成CSV文件的建议:

import csv
d1 = {1: [(3456,12),(4521,78)],
      2: [(5478,45),(5609,43)],
      3: [(8756,34),(6721,90)] }

d2 = {1: [(34,1),(4,7)],
      2: [(58,5),(56,4)],
      3: [(87,3),(67,9)] }

d3 = {1: [(111,22),(333,44)],
      3: [(1000,300),(2000,400)] }

d4 = {'AAA': [('arrze','iifuiyu')],
      'BBB': [(575757,'434343434')] }

def yi(input):
    for user_id,d in input:
        for i in d:
            for tu in d[i]:
                    yield [user_id, i, tu[0], tu[1]]

def csvcompl(fn,ds):           
    with open(fn,'ab') as cc:
        cr = csv.writer(cc)
        cr.writerows(yi(ds))

ds = (('Lavillenie',d1),('Abba',d2),(987654321,d3))
csvcompl('fifiroro.csv',ds)
csvcompl('fifiroro.csv',(('OPO',d4),))

with open('fifiroro.csv','r') as f:
    print f.read()

结果

Lavillenie,1,3456,12
Lavillenie,1,4521,78
Lavillenie,2,5478,45
Lavillenie,2,5609,43
Lavillenie,3,8756,34
Lavillenie,3,6721,90
Abba,1,34,1
Abba,1,4,7
Abba,2,58,5
Abba,2,56,4
Abba,3,87,3
Abba,3,67,9
987654321,1,111,22
987654321,1,333,44
987654321,3,1000,300
987654321,3,2000,400
OPO,AAA,arrze,iifuiyu
OPO,BBB,575757,434343434