是否可以使用 csv.DictReader 保持列顺序? [英] Is it possible to keep the column order using csv.DictReader?
问题描述
例如,我的 csv 列如下:
ID, ID2, Date, Job No, Code
我需要以相同的顺序写回列.dict
立即打乱了顺序,所以我认为这更像是读者的问题.
Python 的 dict
不维护 3.6 之前的顺序(但无论如何,在那个版本中 csv.DictReader
类被修改为返回 OrderedDict
s).
但是,您正在使用的 csv.DictReader
实例(在您阅读第一行之后!-)确实 有一个 .fieldnames
字符串列表,按顺序是.
所以,
用于 myReader 中的 rowdict:打印 ['%s:%s' % (f, rowdict[f]) for f in myReader.fieldnames]
将向您显示订单确实得到维护(当然在 .fieldnames
中,NEVER 在 dict
中 - 这在本质上是不可能的Python!-).
因此,假设您想以相同的列顺序读取 a.csv
和写入 b.csv
.使用普通的读写器太容易了,所以你想改用 Dict 变种;-).嗯,一种方法是...:
导入csva = open('a.csv', 'r')b = open('b.csv', 'w')ra = csv.DictReader(a)wb = csv.DictWriter(b, None)对于 ra 中的 d:如果 wb.fieldnames 是 None:# 初始化并写入 b 的头文件dh = dict((h, h) for h in ra.fieldnames)wb.fieldnames = ra.fieldnameswb.writerow(dh)wb.writerow(d)b.关闭()关闭()
假设您在 a.csv
中有标题(否则您不能在其上使用 DictReader)并且希望 b.csv
中有相同的标题.>
For example, my csv has columns as below:
ID, ID2, Date, Job No, Code
I need to write the columns back in the same order. The dict
jumbles the order immediately, so I believe it's more of a problem with the reader.
Python's dict
s do NOT maintain order prior to 3.6 (but, regardless, in that version the csv.DictReader
class was modified to return OrderedDict
s).
However, the instance of csv.DictReader
that you're using (after you've read the first row!-) does have a .fieldnames
list of strings, which IS in order.
So,
for rowdict in myReader:
print ['%s:%s' % (f, rowdict[f]) for f in myReader.fieldnames]
will show you that the order is indeed maintained (in .fieldnames
of course, NEVER in the dict
-- that's intrinsically impossible in Python!-).
So, suppose you want to read a.csv
and write b.csv
with the same column order. Using plain reader and writer is too easy, so you want to use the Dict varieties instead;-). Well, one way is...:
import csv
a = open('a.csv', 'r')
b = open('b.csv', 'w')
ra = csv.DictReader(a)
wb = csv.DictWriter(b, None)
for d in ra:
if wb.fieldnames is None:
# initialize and write b's headers
dh = dict((h, h) for h in ra.fieldnames)
wb.fieldnames = ra.fieldnames
wb.writerow(dh)
wb.writerow(d)
b.close()
a.close()
assuming you have headers in a.csv
(otherewise you can't use a DictReader on it) and want just the same headers in b.csv
.
这篇关于是否可以使用 csv.DictReader 保持列顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!