![](/img/trans.png)
[英]Reading a specific row & columns of data in a text file using Python 2.7
[英]Reading a specific row & columns of data in a text file
我是Python的新手,我需要從文本文件(.txt)中提取數據。 我下面有一個文本文件,我需要從文本下面的第三欄中獲取數據。 我需要將文本放入python列表中
Version 3.6 CE-QUAL-W2
Lagoa das Furnas - 1 Ramo
Default hydraulic coefficients
Default light absorption/extinction coeffients
JDAY DLT ELWS T2
4.0 5.0 6.0 7.0
3.0 4.0 5.0 6.0
3.0 5.0 7.0 6.0
我已經試過了,但是行不通,我得到了所有行
a=np.genfromtxt('file.txt', skip_header=5)
#updated
L = []
for index, line in enumerate(open('data.txt')):
if index <= 4: #skip first 5 lines
continue
else:
L.append(line.split()[2]) #split on whitespace and append value from third columns to list.
print(L)
#[6.0, 5.0, 7.0]
如果您有一個看起來像所示的文件,則可以跳過標題行,並使用np.genfromtxt
僅抓取一列,如下所示:
np.genfromtxt('filename.txt', skip_header=5, usecols=2)
請注意,我寫了usecols = 2,它獲得了第三列(col 0是第一列)。 您可以使用以下列表獲得多個列: usecols=[0,2]
,它將抓住第一和第三列。
In [105]: from StringIO import StringIO
In [106]: s = StringIO("""Version 3.6 CE-QUAL-W2
.....: Lagoa das Furnas - 1 Ramo
.....: Default hydraulic coefficients
.....: Default light absorption/extinction coeffients
.....: JDAY DLT ELWS T2
.....: 4.0 5.0 6.0 7.0
.....: 3.0 4.0 5.0 6.0
.....: 3.0 5.0 7.0 6.0""")
In [107]: np.genfromtxt(s, skip_header=5, usecols=2)
Out[107]: array([ 6., 5., 7.])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.