#1
  1. Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    23
    Rep Power
    0

    Question deleting lines from a file


    Ok, I did a search and can't seem to find the exact solution to my problem. In windows, I'm trying to delete specific lines from some files. The line number is static. I can get linecache to display the correct line, but I can't seem to figure out how to delete that line.

    I found some code that supposedly deletes the last line of a file. I figured I could tweak that code and use it but it doesn't work for me.

    Can someone kick me in the right direction? Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    12
    read the file line by line and write them to an intermediate file. skip the line you don't want. move the intermediate file to the location your previous file.
  4. #3
  5. Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    23
    Rep Power
    0
    readlines() will iterate through the lines, but I can't seem to figure out how to skip the ones I don't want. I had this code:

    Code:
    fp = open('C:\\filenme.txt', 'rw')
    lines = fp.readlines()
    del lines[10:13]
    fp.close()
    But that doesn't really work. I know I'm missing the part where I write the file again and the del lines should be removing lines 10 through 13, but I'm not confident that I wrote that correctly either.

    Thanks for the hint though.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    12
    Simplistic:
    Code:
    :
    for index, line in enumerate(open('document')):
        if index != 5:
            print >>open('intermediate', 'a'), line,
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Another solusion, a mix of the too aproches really.

    Code:
    #!/usr/bin/env python
    
    lines = file('file.txt', 'r').readlines()
    del lines[slice:to:delete]
    file('file.txt', 'w').writelines(lines)
    Just replace the bold bit with the line number you want to delete - remembering that lists/arrays start with 0 and watch that anoying line go bye bye. But your example should work all you have to do is write the data out with writelines()

    The draw back being that this aproch reads the whole file into memory but then Python programs do that every day so don't worry about it .

    Have fun,

    Mark.
    Last edited by netytan; May 25th, 2004 at 11:47 PM.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo