代码之家  ›  专栏  ›  技术社区  ›  Captain Patches

索引超出范围,文件读取行

  •  0
  • Captain Patches  · 技术社区  · 7 年前

    我创建了一个列表 h 但是,当我尝试运行代码时,我得到了新文件的内容:

    IndexError: list index out of range
    

    这就是我所拥有的,我的代码是否没有创建列表?

    def lab6 (fname):
        """writes in new file with text from existing file"""
        f = open('lab6.txt','a+')
        s = open(fname, 'r', encoding = "ISO-8859-1")
        sc = s.readlines() #creates a list with items in s
        f.write(sc[0]) #copy first line
        #skip next 18 lines
        f.write(str(sc[19:28])) #copy next 9 lines to lab6 
        h = f.readlines() #puts contents of lab6 into list
        print(h) #prints that list
        t = h [2] #retrieve 3rd item in list
        print(t.range(0,3)) #print 1st 3 letters of 3rd item in list
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Barmar    7 年前

    您需要返回到文件的开头,以便读取刚才写的内容。否则,它将从当前文件位置开始读取,但没有可读取的内容,因此 h 是空列表。

    f.seek(0)
    

    之前

    h = f.readlines()
    

    range() 不是提取子字符串的方法,请使用切片表示法。

    print(t[:3])
    

    打印的前3个字符 t