索引超出范围,文件读取行
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
的前3个字符。
我用新文件的内容创建了一个列表 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
的前3个字符。