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

查看:601
本文介绍了是否可以使用Python csv DictReader保持列顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我的csv具有如下列:


ID,ID2,日期,工作号, b $ b

我需要以相同的顺序写回列。

解决方案

Python的 dict 不保持顺序。



但是, csv.DictReader .fieldnames 字符串列表,

  

对于myReader中的rowdict:
print ['%s:%s'%(f,rowdict [f])for f in myReader.fieldnames]

会显示订单确实维护( .fieldnames 当然,从不 dict - 这在Python本质上是不可能的 - )。



所以,假设你想读 a.csv 并以相同的列顺序写入 b.csv 。使用plain reader和writer太容易了,所以你想使用Dict品种代替;-)。嗯,一种方法是...:

  import csv 

a = open('a.csv ','r')
b = open('b.csv','w')
ra = csv.DictReader(a)
wb = csv.DictWriter b
$ b for d in ra:

如果wb.fieldnames是None:
#初始化并写入b的标题
dh = dict((h,h)在ra.fieldnames高)
wb.fieldnames = ra.fieldnames
wb.writerow(DH)

wb.writerow(四)

假设您在<$中有标题,则b.close()
a.close()



c $ c> 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 dicts do NOT maintain order.

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.

这篇关于是否可以使用Python csv DictReader保持列顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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