Python Forum

Full Version: Replacing variable in a split string and write new file python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to open a modelica file, change a variable in a line
ex. parameter Modelica.SIunits.Height Hfsc = 3.7 "ground floor";
I need to change the Hfsc = 3.7 to Height = 2 and then save the changes in a new file.
It should be something like this:
Modelica.SIunits.Height Height = 2 "ground floor";

I can split the line, put replace a variable with float
and then writing the file as new file using
open with ('new_file.mo','w') as new file:

code:

path = '/Users/project.mo'
with open(path, 'r') as f:
for line in f:
Height = 2 # defined a variable
float = 3.7 # do I need to define the 3.7 as a float?
if "parameter Modelica.SIunits.Height Hfsc" in line
str2 = "Hfsc" print(line.find(str2))
print(line.find('=', 37))
print(line.find('"', 49))
indices = [0, 44, 55]
parts = [line[i:j] for i, j in zip(indices, indices[1:] [None])# indices to identify the splitting position of the string

print(parts)
Output:
parameter Modelica.SIunits.Height ', 'Hfsc = 3.7 ', '"ground floor";\n']
Usage: python3 sample.py > project.mo.new

#!/usr/bin/python3

path = 'project.mo'
old  = 'Modelica.SIunits.Height Hfsc = 3.7'
new  = 'Modelica.SIunits.Height Height = 2'
with open(path, 'r') as f:
    for line in f:
        line = line.replace(old, new)
        print(line, end='')