选取一个txt文件,这里就以《Python遥感图像处理应用篇(四):python如何使用numpy读取遥感图像光谱值》中计算得到的txt作为样本数据吧
这个txt里面又307981行数据,第一行为字段名称,其他都是遥感图像光谱值和编码信息。
数据前面有不少零值,后面绝大多数不为0值。
import io
import linecache
import numpy as np
f=open("OLI8_12340_20190817_testData.txt","r",encoding="utf-8")
for line in range(2000,2010):
# get the content of line
theline=linecache.getline("OLI8_12340_20190817_testData.txt",line) # 第一个参数指读取的文件,第二个参数指文件的行数
print(theline)
f.close()
读取txt中指定行的内容运行结果
1998,1999,507,369,603,458,3800,0,252
1999,2000,529,382,644,583,3581,0,371
2000,2001,574,442,741,724,3812,0,361
2001,2002,616,440,757,681,3966,0,318
2002,2003,620,431,735,599,3635,0,210
2003,2004,777,535,825,665,2611,0,178
2004,2005,716,536,807,654,3908,0,272
2005,2006,1181,930,1065,966,3679,0,307
2006,2007,1401,1157,1309,1157,3816,0,347
2007,2008,1417,1135,1285,1137,4081,0,366
测试代码段:
import io
import linecache
import numpy as np
theline=linecache.getline("OLI8_12340_20190817_testData.txt",2000) # 读取2000行数据为字符串
print(theline)
arr=np.array((theline.split(",")))
print(arr)
运行结果,将后面的换行符也读取了
['1998' '1999' '507' '369' '603' '458' '3800' '0' '252\n']