how to update contents of file in python
Question: 
    def update():
        global mylist
        i = j = 0
        mylist[:]= [] 
        key = input("enter student's tp")
        myf = open("data.txt","r+")
        ml = myf.readlines()
        #print(ml[1])
        for line in ml:
          words = line.split()
          mylist.append(words)
        print(mylist)
        l = len(mylist)
        w = len(words)
        print(w)
        print(l)
        for i in range(l):
            for j in range(w):
                print(mylist[i][j])
    ##            if(key == mylist[i][j]):
    ##                print("found at ",i,j)
    ##                del mylist[i][j]
    ##                mylist[i].insert((j+1), "xxx")
    

below is the error

> print(mylist[i][j])
>
> IndexError: list index out of range

I am trying to update contents in a file. I am saving the file in a list as
lines and each line is then saved as another list of words. So "mylist" is a
2D list but it is giving me error with index


Answer: Your `l` variable is the length of the _last_ line list. Others could be
shorter.

A better idiom is to use a `for` loop to iterate over a list. But there is an
even better way.

It appears you want to replace a "tp" (whatever that is) with the string `xxx`
everywhere. A quicker way to do that would be to use regular expressions.

    
    
    import re
    
    with open('data.txt') as myf:
        myd = myf.read()
    newd = re.sub(key, 'xxx', myd)
    with open('newdata.txt', 'w') ad newf:
        newf.write(newd)
    

