Search code examples
pythonlistfileindexingfwrite

Index out of range, file readlines


I created a list h with the contents of the new file, however, when I try to run the code I get:

IndexError: list index out of range

This is what I have, is my code not creating a list?

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

Solution

  • You need to seek back to the beginning of the file in order to read what you just wrote. Otherwise it starts reading from the current file position, but there's nothing there to read, so h is an empty list.

    Put

    f.seek(0)
    

    before

    h = f.readlines()
    

    And range() is not the method for extracting a substring, use slice notation.

    print(t[:3])
    

    to print the first 3 characters of t.