Chris
Chris

Reputation: 27

Remove all text after last occurence in file

I have a bunch of lines inside a text file that looks like this

STANGHOLMEN_BVP01_03_ME41_DELTAT_PV
STANGHOLMEN_TA02_TF01_FO_OP
STANGHOLMEN_VV01_PV01_SP2
STANGHOLMEN_VS01_GT11_EFFBEG_X1

I am trying to remove the text after the last occurrence of _

So this is how i try to make my text look

STANGHOLMEN_BVP01_03_ME41_DELTAT
STANGHOLMEN_TA02_TF01_FO
STANGHOLMEN_VV01_PV01
STANGHOLMEN_VS01_GT11_EFFBEG

its usually around 700 lines, Best way to do this?

Upvotes: 0

Views: 29

Answers (4)

Chris
Chris

Reputation: 27

with open("f_in.txt") as f_in, open("f_out.txt","w") as f_out:
     for line in f_in:
             f_out.write(line.rsplit('_', maxsplit=1)[0])
             f_out.write("\n")

This worked, however now all my text is in a long line, before it was sorted in lines.

Upvotes: 0

Joe Ferndz
Joe Ferndz

Reputation: 8508

You can use rsplit() and use the index[0] value.

For example if txt = 'STANGHOLMEN_VS01_GT11_EFFBEG_X1

txt1 = txt.rsplit('_',1)[0] will give you the values upto EFFBEG.

Upvotes: 0

abc
abc

Reputation: 11929

You can parse the file line by line and add the content to a new file. To split the string you can use rsplit with maxsplit=1.

>>> with open("f_in.txt") as f_in, open("f_out.txt","w") as f_out:
...     for line in f_in:
...             f_out.write(line.rsplit('_', maxsplit=1)[0])
...             f_out.write("\n")

Upvotes: 3

rozumir
rozumir

Reputation: 905

You can user rfind() (returning index of substring looking from right side in simple words) from standard library, it will be the simplest way, but not so reliable.

last_index = string.rfind("_")

Next you have to slice yours string

new_string = string[:index]

Upvotes: 0

Related Questions