0

I have a file formated like this:

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

I want to process the file so that all blocks with second line is 0 can be deleted and left the file as

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

I tried the snippet below, but it can only see the 0/1 then remove the line, but I want to delete the line with floats above 0/1, not the line with floats below 0/1.

f = open(filePath, "r")
lines = f.readlines()
f.close()
f = open(filePath, "w")

for line in lines:
    if "1\n" in line:
        f.write(line)

Is there any other way I can choose which line to include and which not? Or maybe there's a way to process the file backwards?

Mandary
  • 45
  • 1
  • 7

1 Answers1

2

We can use the next() function to get the next element in the file iterable. The shutil module allows us to move the new file, overwriting the original (thanks @JoranBeasley).

import shutil

with open(filePath, 'r') as f, open('new_' + filePath, 'w') as output:
    for 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 one line
0
0.377305882353 0.595870588235 0.353215686275 ...
1 #0/1 for the second line

Output:

0.377305882353 0.595870588235 0.353215686275 ...
1 #0/1 for the second line
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97