我正在尝试将复杂的字典列表写入CSV,但是出现编码和值错误。我还没有真正在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
如果删除编码,则会得到:io.UnsupportedOperation: write
。
这是我要写入CSV文件的数据的示例,标头是诸如code
和hid
之类的键:
[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([...])]
答案 0 :(得分:1)
CSV代表逗号分隔的值。此格式包含纯文本。
此外,'rb'
表示作为二进制文件的 read r
文件 b
,与纯文本不一致。< / p>
尝试使用'wt'
或仅使用'w'
来真正写入纯文本文件。
Check the python docs,以详细了解open()
函数。
我想出了这个解决方案:
csv.writer
被csv.DictWriter
代替,keys
进入writer.writeheader()
keys
插入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)
一行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
中的结果是:
<tr *ngFor="let record of records; let i = index">
<td>
<span *ngIf="editingIndex !== i">{{record.userId}}</span>
<input type="text" class="form-control" [(ngModel)]="record.userId" *ngIf="editingIndex === i"/>
</td>
...
<td><button type="button" (click)="editColumn(record, i);">Edit</button></td>
<td><button type="button" (click)="updateColumn(record, i)">Update</button></td>
</tr>
答案 1 :(得分:0)
'rb'
代表“读取为二进制”。因此,它考虑等效于二进制的方式从文件中读取数据。
根据文档,它不需要任何其他参数。 只需使用:
with open("output.csv", 'w') as f:
您可以尝试使用'w'
代替'rb'
模式,只是写入文件。
文档中的文字。...
以二进制模式打开的文件(在mode参数中包括“ b”) 返回内容作为字节对象,无需任何解码。
模式:
'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)