代码之家  ›  专栏  ›  技术社区  ›  backus sompnd

如何将此词典列表转换为csv文件?

  •  106
  • backus sompnd  · 技术社区  · 16 年前

    toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
    

    我应该怎么做才能将其转换成如下所示的csv文件:

    name,age,weight
    bob,25,200
    jim,31,180
    
    7 回复  |  直到 8 年前
        1
  •  349
  •   stackprotector    5 年前
    import csv
    toCSV = [{'name':'bob','age':25,'weight':200},
             {'name':'jim','age':31,'weight':180}]
    keys = toCSV[0].keys()
    with open('people.csv', 'w', newline='')  as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()
        dict_writer.writerows(toCSV)
    
        2
  •  26
  •   Marc Maxmeister    7 年前

    在python中,3件事有点不同,但是更简单,更不容易出错。最好告诉CSV文件应该打开 utf8 编码,因为它使数据对其他人更具可移植性(假设您不使用更严格的编码,如 latin1 )

    import csv
    toCSV = [{'name':'bob','age':25,'weight':200},
             {'name':'jim','age':31,'weight':180}]
    with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
        fc = csv.DictWriter(output_file, 
                            fieldnames=toCSV[0].keys(),
    
                           )
        fc.writeheader()
        fc.writerows(toCSV)
    
    • 请注意 csv 在python3中需要 newline='' 参数,否则在excel/opencalc中打开时,CSV中会出现空行。

    pandas 模块。我发现它更能容忍编码问题,而且 在加载文件时,pandas会自动将csv中的字符串数字转换为正确的类型(int、float等)。

    import pandas
    dataframe = pandas.read_csv(filepath)
    list_of_dictionaries = dataframe.to_dict('records')
    dataframe.to_csv(filepath)
    

    注:

    • 如果您给文件指定了路径,pandas将负责为您打开该文件,并且默认为 在python3中,并找出标题。
    • dataframe.to_dict('records')
    • pandas还可以更轻松地控制csv文件中列的顺序。默认情况下,它们是按字母顺序排列的,但您可以指定列顺序。加香草 csv文件 模块,你需要给它一个 OrderedDict 或者它们将以随机顺序出现(如果使用python<3.5). 请参见: Preserving column order in Python Pandas DataFrame 更多。
        3
  •  17
  •   hamed    11 年前

    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'})
    
        4
  •  7
  •   flowerflower    9 年前

    因为@User和@BiXiC请求帮助使用UTF-8,这里是@Matthew解决方案的一个变体(我不能评论,所以我回答。)

    import unicodecsv as csv
    toCSV = [{'name':'bob','age':25,'weight':200},
             {'name':'jim','age':31,'weight':180}]
    keys = toCSV[0].keys()
    with open('people.csv', 'wb') as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()
        dict_writer.writerows(toCSV)
    
        5
  •  2
  •   eddygeek    8 年前

    write_csv 函数是泛型的):

    def gen_rows():
        yield OrderedDict(name='bob', age=25, weight=200)
        yield OrderedDict(name='jim', age=31, weight=180)
    
    def write_csv():
        it = genrows()
        first_row = it.next()  # __next__ in py3
        with open("people.csv", "w") as outfile:
            wr = csv.DictWriter(outfile, fieldnames=list(first_row))
            wr.writeheader()
            wr.writerow(first_row)
            wr.writerows(it)
    

    :此处使用的orderedict构造函数仅保留python中的顺序>3.4. 如果顺序很重要,请使用 OrderedDict([('name', 'bob'),('age',25)]) 形式。

        6
  •  2
  •   marc_s MisterSmith    8 年前
    import csv
    
    with open('file_name.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(('colum1', 'colum2', 'colum3'))
        for key, value in dictionary.items():
            writer.writerow([key, value[0], value[1]])
    

    这是将数据写入的最简单方法 .csv文件

        7
  •  1
  •   Souvik Daw    6 年前
    import csv
    toCSV = [{'name':'bob','age':25,'weight':200},
             {'name':'jim','age':31,'weight':180}]
    header=['name','age','weight']     
    try:
       with open('output'+str(date.today())+'.csv',mode='w',encoding='utf8',newline='') as output_to_csv:
           dict_csv_writer = csv.DictWriter(output_to_csv, fieldnames=header,dialect='excel')
           dict_csv_writer.writeheader()
           dict_csv_writer.writerows(toCSV)
       print('\nData exported to csv succesfully and sample data')
    except IOError as io:
        print('\n',io)