2013-10-25 33 views
-1

我有一個數據文件,它有100行,我想要創建一個字典,它跳過前兩行,然後創建一個字典,並以行作爲值枚舉鍵。Python:從文件中跳過

myfile = open(infile, 'r') 
d={} 
with myfile as f: 
    next(f) 
    next(f) 
    for line in f: 

這是我得到了什麼,我沒怎麼使用iteritems(),枚舉(),或itervalues(),但我覺得我想我會用他們或許不是,如果有人可以幫助我。

+0

感謝您發佈您的代碼,但請在您的問題中多加一點說明:您有什麼問題,您期望的結果是什麼,以及[您嘗試過什麼](http://whathaveyoutried.com)遠? –

回答

0

這只是我的頭頂,所以肯定會有改進的空間。


myfile = open(infile, 'r') # open the file 
d = {}      # initiate the dict 

for line in myfile:  # iterate over lines in the file 
    counter = 0    # initiate the counter 
    if counter <= 1:   # if we have counted under 2 iterations 
    counter += 1   # increase the counter by 1 and do nothing else 
    else:     # if we have counted over 2 iterations 
    d[counter - 2] = line # make a new key with the name of lines counted (taking in to consideration the 2 lines precounted) 
    counter += 1   # increase the counter by 1 before continuing 

我不能我的頭頂記得在代碼這將是最好關閉該文件,但做一些試驗和閱讀thisthis。另一次是開始的好地方通常是googlepython docs

+1

使用'with'語句而不是顯式關閉文件可能會更好 - 即使出現錯誤,'with'塊也會關閉文件。 – kojiro

1

可以做這樣的事情:

from itertools import islice 
with open(infile, 'r') as myfile: 
    d = dict(enumerate(islice(myfile, 2, None))) 

但我想我明白了爲什麼要跳過前兩行 - 你肯定不想linecache