2011-03-10 48 views
1

我有一個製表符分隔文件製表符分隔文件到字典(python)

如何將此文件輸入字典?

+0

爲什麼你想爲每一行單獨的字典? – 2011-03-10 07:51:26

+0

按字母排序。我想我是非常新的python ... – notrockstar 2011-03-10 07:52:35

+0

@Mark,感謝您的建議。我會繼續並遵循你的建議。 – notrockstar 2011-03-10 08:02:06

回答

3
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 
+0

你可以用'DictReader'作爲參數來調用'list'來代替迭代和追加。 – icktoofay 2011-03-10 08:09:16

+0

好點!我會相應更新。 – 2011-03-10 08:09:43

+0

@Mahmoud Abdelkader:謝謝! – notrockstar 2011-03-10 08:15:53

3

您可以使用csv模塊及其DictReader class

+0

和一個適當的'方言'。 – 2011-03-10 07:52:15

+0

如何跳過前兩行? – notrockstar 2011-03-10 07:53:48

+2

@notrockstar:如果您確定前兩行始終是註釋,您可以在創建「DictReader」之前對文件對象調用'readline'兩次。 – icktoofay 2011-03-10 07:56:11