Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to remove lines found between 2 concrete strings

Tags:

python

I have put together a script which reads a text file as below,

*NODE
100000,1144.,-447.2639,339.0315
100001,1144.,-454.7716,342.956
100003,1144.,-448.2677,343.6241
100004,1144.,-454.8527,338.5432
*ELEMENT, TYPE=C3D6
228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

and writes only

228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

but I actually want it to write

*ELEMENT, TYPE=C3D6
228888,103103,103111,106773,186164,186165,196339
228889,103111,103232,106773,186165,186184,196339
228890,106773,106911,106912,196339,196457,196453

below is the code that I wrote,

with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile:
    for line in oldfile:
        if writing:
            if "*NODE" in line:
                writing = False
            else:
                newfile.write(line)
        elif "*ELEMENT" in line:
            writing = True
newfile.write
like image 739
A.iti Avatar asked Feb 16 '26 00:02

A.iti


1 Answers

with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile:
    for line in oldfile:
        if writing:
            if "*NODE" in line:
                writing = False
            else:
                newfile.write(line)
        elif "*ELEMENT" in line:
            newfile.write(line)
            writing = True
newfile.write

You were not writing the line which contains *ELEMENT. But I would suggest generally doing all of this using regex / a bit of shell scripting.

like image 58
Abel Riboulot Avatar answered Feb 17 '26 14:02

Abel Riboulot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!