是否可以使用csv.DictReader保持列顺序? [英] Is it possible to keep the column order using csv.DictReader?

查看:180
本文介绍了是否可以使用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 dicts do NOT maintain order prior to 3.6 (but, regardless, in that version the csv.DictReader class was modified to return OrderedDicts).

但是,您正在使用的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中,当然是中的 Never -在Python中本质上是不可能的!-).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆