分割线索引

时间:2016-05-24 06:58:32

标签: python split

我有一个输入文件:

.......  
.......  
# Start  
A 2 100  
B 3 200  
C 4 1000  

# End  
........
........

我想将第2列打印为:

2  
3  
4 

我的代码是:

with open("my_file.txt") as f:  
     parsing=False  
     for line in f:  
        if line.startswith("# Start"):  
            parsing = True  
        elif line.startswith("# End"):  
            parsing = False  
        if parsing:  
            line = line.split()  
            if line:  
               print line[1]  

但是,我输出错误为

print line[1]  
IndexError: list index out of range  

如果我使用打印行[0],则会打印:

A  
B  
C 

我出错的任何建议

2 个答案:

答案 0 :(得分:3)

在访问数组[length]

中的第二个元素之前,

检查size的{​​{1}} / line [{1}}之后]

尝试;

line.split()

答案 1 :(得分:1)

根据您的评论,您还必须忽略破折号线:

with open("my_file.txt") as f:  
    parsing = False  
    for line in f:  
        if line.startswith("# Start"):  
            parsing = True
        elif line.startswith("# End"):  
            parsing = False  
        elif line.startswith("---"):  
            pass # ignore these lines 
        elif parsing:  
            line = line.split()  
            if line:
                print line[1]