delete lines from file in python -


i have file formated this:

#1  0.13297254902 0.324803921569 0.434835294118 ...#many floats in 1 line #2  0 #3  0.377305882353 0.595870588235 0.353215686275 ... #4  1 #0/1 second line  #5  .... 

i want process file blocks second line 0 can deleted , left file as

#1  0.377305882353 0.595870588235 0.353215686275 ... #2  1 #3  0.403529411765 0.341654901961 0.379278431373 ...  #4  1 #now 1s #5  ..... 

i tried snippet below, can see 0/1 remove line, want delete line floats above 0/1, not line floats below 0/1.

f = open(filepath, "r") lines = f.readlines() f.close() f = open(filepath, "w")  line in lines:     if "1\n" in line:         f.write(line) 

is there other way can choose line include , not? or maybe there's way process file backwards?

we can use next() function next element in file iterable. shutil module allows move new file, overwriting original (thanks @joranbeasley).

import shutil  open(filepath, 'r') f, open('new_' + filepath, 'w') output:     line in f:         n = next(f)         if n != '0\n':             output.write(line+n)  shutil.move("new_" + filepath, filepath) 

input:

0.13297254902 0.324803921569 0.434835294118 ...#many floats in 1 line 0 0.377305882353 0.595870588235 0.353215686275 ... 1 #0/1 second line 

output:

0.377305882353 0.595870588235 0.353215686275 ... 1 #0/1 second line 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -