回答
import csv
with open(filename) as file_object:
# skip the first two lines
file_object.next()
file_object.next()
list_of_dicts = list(csv.DictReader(file_object, dialect='excel-tab'))
# list_of_dicts now will contain a list of dictionaries extracted from the file
你可以用'DictReader'作爲參數來調用'list'來代替迭代和追加。 – icktoofay 2011-03-10 08:09:16
好點!我會相應更新。 – 2011-03-10 08:09:43
@Mahmoud Abdelkader:謝謝! – notrockstar 2011-03-10 08:15:53
您可以使用csv
模塊及其DictReader
class。
和一個適當的'方言'。 – 2011-03-10 07:52:15
如何跳過前兩行? – notrockstar 2011-03-10 07:53:48
@notrockstar:如果您確定前兩行始終是註釋,您可以在創建「DictReader」之前對文件對象調用'readline'兩次。 – icktoofay 2011-03-10 07:56:11
爲什麼你想爲每一行單獨的字典? – 2011-03-10 07:51:26
按字母排序。我想我是非常新的python ... – notrockstar 2011-03-10 07:52:35
@Mark,感謝您的建議。我會繼續並遵循你的建議。 – notrockstar 2011-03-10 08:02:06