python将dict数据加载到csv文件

时间:2016-04-28 01:38:23

标签: python csv dictionary

我有一个字典文件,我想加载到csv文件,其中键是我的列,每次新数据读入时,值将继续追加到新行。 我的代码:

B

但我得到

def move(inp):
    if inp == 1:
        one = " X |\t|\n_____________\n   |\t|\n_____________\n   |\t|"
        print one
    elif inp == 2:
        two = "   | X |\n_____________\n   |\t|\n_____________\n   |\t|"
        print two
    elif inp == 3:
        three = "   |\t| X\n_____________\n   |\t|\n_____________\n   |\t|"
        print three
    elif inp == 4:
        four = "   |\t|\n____________\n X |\t|\n_____________\n   |\t|"
        print four
    elif inp == 5:
        five = "   |\t|\n_____________\n   | X  |\n_____________\n   |\t|"
        print five
    elif inp == 6:
        six = "   |\t|\n_____________\n   |\t| X \n_____________\n   |\t|"
        print six
    elif inp == 7:
        seven = "   |\t|\n_____________\n   |\t|\n_____________\n X |\t|"
        print seven
    elif inp == 8:
        eight = "   |\t|\n_____________\n   |\t|\n_____________\n   | X |"
        print eight
    elif inp == 9:
        nine = "   |\t|\n_____________\n   |\t|\n_____________\n   |\t| X "
        print nine

我找不到问题。

1 个答案:

答案 0 :(得分:0)

您的程序出现StopIteration错误,因为您的iterable(即您的文件)中没有其他值。

解决此问题的一种方法是实施一些error handling

with open ('master_result.csv','r+b') as csvFile:
    try:
        # check if the necessary headers exist in your 
        # csvFile already.
        header = next(csv.reader(csvFile))
        dict_writer = csv.DictWriter(csvFile, header)
        dict_writer.writerow(dict1)
    except StopIteration:
        # If the headers don't already exist, 
        # use the keys of Dict1 to establish them.
        header = dict1.keys()
        dict_writer = csv.DictWriter(csvFile, header)
        dict_writer.writeheader()
        dict_writer.writerow(dict1) 

# 'master_result.csv' output if dict1 = {key1: value1, key2: value2, key3: value3}:
# key1    key2    key3
# value1  value2  value3

您还可以使用with循环包裹for块以迭代多个词典(例如,词典列表)并包含输出文件中的所有值。这只是猜测,但我认为这就是你的意思:

  

...每次新数据读入时,值都将继续附加到新行。