-2

I want to import a txt file and remove full lines (or any part of the line) which starts with "--".

as an example: (original)

ACTNUM                                 -- Generated : Petrel
-- Property name in Petrel : R2_ACTNUM
  2624*1 0 0 0 169*1 5*0 1 1 1 1 6*0 160*1 0 0 18*1 0 0 152*1 0 0 27*1 0 145*1 0 35*1 7*0 132*1 0 350*1 0 33*1 0 0 139*1 0 174*1 0 1

i want it to become:

ACTNUM                                
  2624*1 0 0 0 169*1 5*0 1 1 1 1 6*0 160*1 0 0 18*1 0 0 152*1 0 0 27*1 0 145*1 0 35*1 7*0 132*1 0 350*1 0 33*1 0 0 139*1 0 174*1 0 1

I hope someone can help me out.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
sadi
  • 1
  • 1
  • Possible duplicate of [Remove Sub String by using Python](https://stackoverflow.com/questions/8703017/remove-sub-string-by-using-python) – Madplay Jul 05 '19 at 12:05
  • Welcome to SO ! :) I strongly suggest you to check at existing questions, this has been done and redone – BlueSheepToken Jul 05 '19 at 12:08
  • For example: https://stackoverflow.com/questions/1706198/python-how-to-ignore-comment-lines-when-reading-in-a-file – mkrieger1 Jul 05 '19 at 12:11

1 Answers1

0

You can loop through the input file, process each line, and then write to the output file. Here's how I would do it.

lines = []
with open('file.txt', 'r') as input_f:
    for line in input_f.readlines():
        # the interesting bit
        if '--' in line:
           index = line.index('--') # find where the '--' is
           relevant_part = line[:index].strip()  # get what's before the '--'
           if relevant_part != '':
               # only store it if there is something there.
               lines.append(relevant_part)
        else:
            lines.append(line)

with open('file.txt', 'w') as output_f:
    for line in lines:
        output_f.write(f'{line}\n')
blueteeth
  • 3,330
  • 1
  • 13
  • 23
  • Thanks! This works nicely. only it generates extra space in between of lines. as: ACTNUM 2624*1 0 0 0 169*1 5*0 1 156*1 0 15*1 0 164*1 0 7 62*1 0 105*1 0 0 0 172*1 173*1 0 0 74*1 0 98*1 0 – sadi Jul 05 '19 at 12:17
  • As a side note, I strongly suggest to not store the lines in a list, and write them directly in the new file. Furthermore, you could do smthing like `cleaned_line = line.split('--', 1)[0]` – BlueSheepToken Jul 05 '19 at 12:19