【问题标题】:Index out of range in python while reading multiple lines from a file从文件中读取多行时,python中的索引超出范围
【发布时间】:2018-07-23 20:15:19
【问题描述】:

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

fname = input("Enter file name: ") 

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

【问题讨论】:

    标签: python list indexing range


    【解决方案1】:

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

    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]) 
    

    【讨论】:

      【解决方案2】:

      如果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 时,您会得到一个空列表。所以没有零元素。

      【讨论】:

        【解决方案3】:

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

        如果你想读行,可以稍微修改一下你的代码,让 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]) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-20
          • 2020-03-28
          • 2015-10-23
          • 1970-01-01
          • 2015-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多