Python open file and delete a line
Question: I need a program that imports a file. My file is:

    
    
    1 abc
    2 def
    3 ghi
    4 jkl
    5 mno
    6 pqr
    7 stu.
    

I want to delete lines 1, 6 and 7.

Iv tried the following to import the file:

    
    
    f = open("myfile.txt","r")
    lines = f.readlines()
    f.close()
    f = open("myfile.txt","w")
    if line = 1:
        f.write(line)
    f.close
    


Answer: You could remove those lines as follows:

    
    
    lines = []
    
    with open('myfile.txt') as file:
        for line_number, line in enumerate(file, start=1):
            if line_number not in [1, 6, 7]:
                lines.append(line)
    
    with open('myfile.txt', 'w') as file:
        file.writelines(lines)
    

By using Python's `with` command, it ensures that the file is correctly closed
afterwards.

