Home > Enterprise >  adding new content above a specific content in file
adding new content above a specific content in file

Time:05-20

I have following text in a file suppose names as myfile.txt.

HWUnit

Configuration
  ConfigInfo
    parm 1
  End ConfigInfo
  ConfigInfo
    EmptyConfig
    ModuleKey     16#0F00
    InAreaSize    0
    OutAreaSize   0
  End ConfigInfo
End Configuration

HWUnitCRC 16#AC7D
End HWUnit

I want to add following content above the line containing text "HWUnitCRC" and save the file.

NewConfiguration
     param1 value1
End NewConfiguration

I have to do this for lot of files and want to write a utility with python3. I am looking for help and template code on how this can be achieved.

Thanks for the help

CodePudding user response:

import sys
f=open(r'C:\Users\user\Desktop\Stack overflow\myfile.txt','r')
x=f.read()
with open (r'C:\Users\user\Desktop\Stack overflow\text.txt','w') as sys.stdout:
    print('NewConfiguration\n    param1 value1\nEnd NewConfiguration\n',x)

CodePudding user response:

A bit inelegant, but this should move you in the right direction.

from pathlib import Path
import re

myfile = Path() / "myfile.txt"

# leading and trailing newline to preserve spacing
string_to_insert = """
NewConfiguration
     param1 value1
End NewConfiguration

"""

with myfile.open() as f:
    text_from_file = f.read()

# match newline character before HWUnitCRC string
pattern = re.compile(
    pattern=r"\n(?=^HWUnitCRC 16#AC7D$)",
    flags=re.MULTILINE,
)

# replace newline character with desired text
new_string = re.sub(
    pattern=pattern,
    repl=string_to_insert,
    string=text_from_file,
)

with myfile.open("w") as f:
    f.write(new_string)
  • Related