Home > Software engineering >  Remove specific string after specific words in python
Remove specific string after specific words in python

Time:04-01

I have couple of lines in a utf encoded text file as shown below

Analog Objects.D-13FT0813.MPM.FormationWater.AccVolumeTotal.ProcessValue    5   "m³"   "Item value"    "
Status Objects.D-13FT1313.MPM.ActiveTemperatureTransmitter.ProcessValue 3   ""  "Item value"    "

What I want is to remove all the text after "ProcessValue" from both the lines and then saved the file again. I have used the following code but didn't get the desired result. Appreciate if some one could help me. My code is

import codecs
with open(r"test.txt", 'r ') as fp:
    lines = fp.readlines()
    fp.seek(0)
    fp.truncate()
    for line in lines:
        split_string = line.split(".ProcessValue")
        line = split_string[0]
        print(line)
        fp.write(line)

CodePudding user response:

This is an easy fix for your problem, I dont know if theres a lot more going on and you absolutely dont want to close the file in between operations, but if that's not the case, opening the file with "w" parameter overwrites the lines

txt = ""
with open(r"test.txt", 'r') as fp:
    for line in fp.readlines():
        line = line.split(".ProcessValue")[0]
        print(line) # unnecessary
        txt  = line   "\n"
with open(r"test.txt", "w") as fp:
    fp.write(txt)

EDIT : Solution to leave ".ProcessValue"

txt = ""
with open(r"test.txt", 'r') as fp:
    for line in fp.readlines():
        splitStr = ".ProcessValue"
        index = line.find(splitStr)
        if index > 0:
            txt  = line[:index   len(splitStr)]   "\n"
with open(r"test.txt", "w") as fp:
    fp.write(txt)
  • Related