Home > Net >  Remove line that contain specific element in a txt file python
Remove line that contain specific element in a txt file python

Time:10-30

I have a txt file with elements:

705.95 117.81 1242.00 252.43 5.02

1036.12 183.52 1242.00 375.00 1.96

124.11 143.43 296.91 230.32 10.70

0.00 0.00 0.00 0.00 4.84

0.00 6.60 112.99 375.00 17.50

0.00 186.66 14.82 375.00 8.23

695.36 162.75 820.66 263.08 12.84

167.61 134.45 417.75 222.10 27.61

0.00 0.00 0.00 0.00 6.86

0.00 0.00 0.00 0.00 11.76

I want to delete lines that contains 0.00 0.00 0.00 0.00 as the first four elements of each line, how can I do that using python? Your help is highly appreciated.

CodePudding user response:

with open('file.txt', 'r') as infile:
  with open('output.txt', 'w') as outfile:
    for line in infile:
      if not line.startswith('0.00 0.00 0.00 0.00'):
        outfile.write(line)

Here we open file.txt with your lines for reading and output.txt for writing the result. Then, we iterate over each line of the input file and write the line in the results file if it doesn't start with '0.00 0.00 0.00 0.00'.

CodePudding user response:

If you want to overwrite the files without creating new output files, you can try this. The following code also helps you iterate through all the text files in the current directory.

import glob

for i in glob.glob("*.txt"):
    with open(i, "r ") as f:
        content = f.readlines()

        f.truncate(0)
        f.seek(0)

        for line in content:
            if not line.startswith("0.00 0.00 0.00 0.00"):
                f.write(line)
  • Related