首页 > 解决方案 > 在读取文本文件时提取列值

问题描述

我有一个保存在文本中的文件,其中包含行数。我想逐行读取并尝试在每次迭代中提取第二列和第三列值,并希望对它们进行一些处理。(例如,在读取第一行时在文本文件下面我需要提取值 0.1115 和 0.2 进行计算..

我拥有以下格式并保存在 test.txt 中的数据

/home/sio/testfile 0.1115  0.2  0.8
/home/sio/testfile 0.50  0.4  0.1
/home/sio/testfile 0.9  0.7  0.7
/home/sio/testfile 0.4  0.8  0.4
/home/sio/testfile 0.7  0.9  2.3

我尝试了下面的代码,但它给了我错误:

import numpy as np

a = open("test.txt","r")
b = a.readlines()
a.close()
  while readline(b)
        secondcolumn=
        thirdcolumn=
    

标签: pythonnumpyfor-loopwhile-loop

解决方案


import numpy as np

a = open("test.txt","r")
b = a.readlines()
a.close()
for line in b:
    columns=line.split()
    if len(columns)>=2:
        col2=columns[1]
        col3=columns[2]
        print(col2,col3)

推荐阅读