是否可以使用csv.DictReader保持列顺序? [英] Is it possible to keep the column order using csv.DictReader?
问题描述
例如,我的csv具有以下列:
For example, my csv has columns as below:
ID, ID2, Date, Job No, Code
我需要以相同的顺序写回列. dict
立即使顺序混乱,所以我认为这对读者来说是一个更大的问题.
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的dict
不会保持3.6之前的顺序(但是,不管在那个版本中,csv.DictReader
类都被修改为返回OrderedDict
s ).
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).
但是,您正在使用的csv.DictReader
的实例(在阅读第一行之后!-)确实有一个.fieldnames
字符串列表,其中 IS .
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.
所以
for rowdict in myReader:
print ['%s:%s' % (f, rowdict[f]) for f in myReader.fieldnames]
会告诉您确实保持了顺序(在.fieldnames
中,当然是
will show you that the order is indeed maintained (in .fieldnames
of course, NEVER in the dict
-- that's intrinsically impossible in Python!-).
因此,假设您要读取a.csv
并以相同的列顺序写入b.csv
.使用普通的读取器和写入器太容易了,因此您想使用Dict变体;-).嗯,一种方法是...:
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()
假设您在a.csv
中有标头(否则您不能在其上使用DictReader),并且希望在b.csv
中仅具有相同的标头.
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屋!