2012-07-12 70 views
0

我想從文件中獲取數據並將它們存儲在向量中,但是我發現了一些困難。 那是我的Python腳本什麼樣子:Python getline()問題

from numpy import array, append 
from linecache import getline 
print 'read file' 
t = [] 
f = open('file.dat', 'r') 
b = getline('f',4).split() 
t.append(int(b[0])) 

運行後,我得到的信息:

t.append(int(b[0])) 
IndexError: list index out of range 

當我檢查出現b是空的:

>>b 
[] 

4號線在file.dat中我有數字4,它只是這一行中的一個條目。 有人知道怎麼回事?我正在使用2.7 Python版本。

+0

你能顯示你的數據嗎? – dangonfast 2012-07-12 20:52:23

回答

1

我相信你的錯誤是,你是用思念linecache.getline你應該做的:

from numpy import array, append 
from linecache import getline 
print 'read file' 
t = [] 
b = getline('file.data',4).split() 
t.append(int(b[0])) 
0

第一個參數爲getline是文件名。

b = getline('file.data',4).split() 
+0

非常感謝您解決問題。 – user1521973 2012-07-12 21:08:19