繁体   English   中英

如何使用python轻松从csv过滤?

[英]How to easily filter from csv with python?

假设我有以下CSV文件:

User ID   Name        Application  

001       Ajohns      ABI
002       Fjerry      Central
900       Xknight     RFC
300       JollK       QDI
078       Demik       Central

是否有一些简单的方法(将其导入到某些数据结构中)? 和/或能够轻松地在python中执行以下操作:

1) Get all user IDs with Application=Central
2) Get the row where name="FJerry" then extract say the "userid" value from
3) Give me the filtered rows for those with "Application=Central" so I can write out to CSV
4) Give me all the rows where Name="Ajohn", and Application="ABI" such that I could easy do a len() to count them up?

是否有一些python库或完成以上操作的最简单方法是什么?

使用DictReader琐碎。 由于您的字段使用制表符分隔,因此您需要通过excel-tab作为方言。

rows是词典列表。

>>> with open(r'd:\file.csv','rb') as f:
...     reader = csv.DictReader(f,dialect='excel-tab')
...     rows = list(reader)
...
>>> [x['User ID'] for x in rows if x['Application'] == 'Central']
['002', '078']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM