简体   繁体   English

使用复杂的列表数据写入 CSV 文件

[英]Writing CSV file with complex list data

I'm trying to write a complex list of dictionaries to CSV, but getting encoding and value errors.我正在尝试将复杂的字典列表写入 CSV,但遇到编码和值错误。 I haven't really worked with data in Python, so I'm new to this.我还没有真正处理过 Python 中的数据,所以我是新手。

import csv

with open("output.csv", 'rb', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f, delimiter=",")
    for row in row_num:  
        writer.writerows(row_num)

 Traceback (most recent call last):
 File "<console>", line 1, in <module>
 ValueError: binary mode doesn't take a newline argument

If I remove the encoding, I get: io.UnsupportedOperation: write .如果我删除编码,我会得到: io.UnsupportedOperation: write

Here is a sample of the data that I want to write to a CSV file with header being the key like code and hid :这是我想写入 CSV 文件的数据示例,其中 header 是键,如codehid

 [OrderedDict([('code', '7nsdjfk'), ('hid', '220'), ('name', 'sdjlnj dkldk slkdlkd'), ('code2', '99'), ('description', 'dmldc skdlmls wsldfml'), ('average', '0'), ('ccr', '0.218'), ('ccr_price', '399'), ('dusk sdks', '603'), ('dcfl lldcml', '3847.9'), ('id', 'sdklcldkcdslkcmsdl202i')]), OrderedDict([ ...]), OrderedDict([...])]

Changing the mode to text-plain将模式更改为纯文本

CSV stands for comma-separated value. CSV 代表逗号分隔值。 This format consists on plain text.这种格式由纯文本组成。

Moreover, 'rb' means read r file as a binary b , which is incongruent with plain-text.此外, 'rb'表示r文件读取为二进制b ,这与纯文本不一致。

Try with 'wt' or just 'w' to actually write a plain-text file.尝试使用'wt'或仅使用'w'来实际编写纯文本文件。

Check the python docs to learn more about the open() function.查看 python 文档以了解有关open()函数的更多信息。

Edit: Write data into file编辑:将数据写入文件

I have come up with this solution:我想出了这个解决方案:

  • csv.writer is replaced by csv.DictWriter , which intakes the keys csv.writercsv.DictWriter取代,它接收keys
  • writer.writeheader() inserts the keys as headers separated by commas writer.writeheader()keys作为以逗号分隔的标题插入
  • writer.writerows(row_num) writes the values into the file, one line per OrderedDict writer.writerows(row_num)将值写入文件,每个OrderedDict一行
from collections import OrderedDict
import csv

row_num = [OrderedDict([('code', '7nsdjfk'), ('hid', '220'), ('name', 'sdjlnj dkldk slkdlkd'), ('code2', '99'), ('description', 'dmldc skdlmls wsldfml'),
                        ('average', '0'), ('ccr', '0.218'), ('ccr_price', '399'), ('dusk sdks', '603'), ('dcfl lldcml', '3847.9'), ('id', 'sdklcldkcdslkcmsdl202i')]),
           OrderedDict([('code', 'a'), ('hid', '1'), ('name', 'b'), ('code2', '1'), ('description', 'c'),
                        ('average', '1'), ('ccr', '0.123'), ('ccr_price', '133'), ('dusk sdks', '133'), ('dcfl lldcml', '1345.9'), ('id', 'abcde')]),
        ]

keys = row_num[0].keys()

with open("output.csv", 'wt', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f, delimiter=",")
    writer = csv.DictWriter(f, keys)
    writer.writeheader()

    # write values
    writer.writerows(row_num)

The results in output.csv are: output.csv中的结果是:

code,hid,name,code2,description,average,ccr,ccr_price,dusk sdks,dcfl lldcml,id
7nsdjfk,220,sdjlnj dkldk slkdlkd,99,dmldc skdlmls wsldfml,0,0.218,399,603,3847.9,sdklcldkcdslkcmsdl202i
a,1,b,1,c,1,0.123,133,133,1345.9,abcde

'rb' stands for 'read as binary'. 'rb'代表“读为二进制”。 So, it reads the data from the file considering equivalent of binary.因此,它考虑等效于二进制文件从文件中读取数据。

It does not take any extra arguments, as per doc.根据文档,它不需要任何额外的参数。 Simply use:只需使用:

with open("output.csv", 'w') as f:

You can try to use 'w' in place of 'rb' mode just to write the file .您可以尝试使用'w'代替'rb'模式来写入文件

Words from the documentation....文档中的话....

Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.以二进制模式打开的文件(包括 mode 参数中的“b”)将内容作为字节对象返回,无需任何解码。

Modes:模式:

'r' - open for reading (default)
'w' - open for writing, truncating the file first
'x' - open for exclusive creation, failing if the file already exists
'a' - open for writing, appending to the end of the file if it exists
'b' - binary mode
't' - text mode (default)
'+' - open a disk file for updating (reading and writing)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM