|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
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
|
|||
|
|||
|
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.
|
|
#3
|
||||
|
||||
|
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. |
|
#4
|
|||
|
|||
|
Simplistic:
Code:
:
for index, line in enumerate(open('document')):
if index != 5:
print >>open('intermediate', 'a'), line,
|
|
#5
|
||||
|
||||
|
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 10:47 PM. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > deleting lines from a file |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|