繁体   English   中英

从文件读取多行时在python中索引超出范围

[英]Index out of range in python while reading multiple lines from a file

我对python中的索引感到困惑。 我正在使用以下代码从文件中读取一行并打印列表中的第一项。 我认为每次读取一行索引都会设置为零。 我的以下代码索引超出范围。 请说明我要去哪里。

fname = input("Enter file name: ") 

fh = open(fname)  
for line in fh:     
 line = line.strip()     
 print(line)      
 b = line.split()  
 print(b[0]) 

如果字符串为空,可能会变坏。

In [1]: line = '     '
In [2]: line = line.strip()
In [4]: b = line.split()
In [5]: b
Out[5]: []
In [6]: b[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-422167f1cdee> in <module>()
----> 1 b[0]

IndexError: list index out of range

也许如下更新您的代码:

fname = input("Enter file name: ") 

fh = open(fname)  
for line in fh:     
    line = line.strip()     
    b = line.split()
    if b: 
        print(b[0]) 

如果line为空白(换句话说,它仅由空格和回车组成),则在line.strip()之后将为空字符串。

>>> line = ""
>>> line.split()[0]

Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    line.split()[0]
IndexError: list index out of range

换句话说,当对空字符串使用split ,将返回一个空列表。 因此不存在零元素。

如前所述,如果行为空白,则会出现索引错误。

如果您想阅读行,也许只需更改一些代码即可让Python为您完成工作

fname = input("Enter file name: ") 
with open(fname) as f
    lines = f.readlines()
# f will be closed at end of With statement no need to take care
for line in lines:     
    line = line.strip()     
    print(line)      
    # following line may not be used, as line is a String, just access as an array
    #b = line.split()
    print(line[0]) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM