如何解析ASCII文件中某一行的某一列?

时间:2017-03-29 20:29:55

标签: python parsing ascii

我正在尝试从我的ASCII文件中的某一行中的某个列中解析出一个字符串值。下面我已经包含了我在这一点上尝试过的内容,我运行此代码时收到的错误是:

Attribute: 'list' object has no attribute 'split'`

代码:

import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')

line = f.readlines(49)
columns = line.split()
time = columns(2)
print (time)

f.close()

1 个答案:

答案 0 :(得分:0)

我会创建一个功能来完成它 请注意,行号和列号从1开始计数,而不是零。

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        for i in range(line_num-1):  # skip over lines before the desired one
            next(file)
        line = next(file)  # read the desired line
        return line.split()[column_num-1]

# sample usage
print(find_line_and_column('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 4, 3))

或者,使用islice()模块中的itertools函数可以更简洁地完成它:

import itertools

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        line = next(itertools.islice(file, line_num-1, None), None) # get line_num-th line
        return line.split()[column_num-1]