2012-10-30 108 views
0

假設我有以下CSV文件:如何使用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庫或什麼是完成上述的最簡單的方法?

+1

你看過[csv模塊](http://docs.python.org/2/library/csv.html)嗎? –

+1

具體'DictReader'? –

回答

1

使用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']