繁体   English   中英

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

[英]Index out of range, file readlines

我用新文件的内容创建了一个列表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

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

f.seek(0)

之前

h = f.readlines()

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

print(t[:3])

打印t的前三个字符。

暂无
暂无

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

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