Python Forum
Replacing variable in a split string and write new file python
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing variable in a split string and write new file python
#1
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']
Reply
#2
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='')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 27,844 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  How to write variable in a python file then import it in another python file? tatahuft 4 864 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,481 Oct-17-2024, 01:15 AM
Last Post: Winfried
  Unable to understand the function string.split() Hudjefa 8 2,268 Sep-16-2024, 04:25 AM
Last Post: Pedroski55
  What does .flush do? How can I change this to write to the file? Pedroski55 3 1,302 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 1,525 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 4,839 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 3,731 Nov-09-2023, 10:56 AM
Last Post: mg24
  Need to replace a string with a file (HTML file) tester_V 1 1,865 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  doing string split with 2 or more split characters Skaperen 22 6,093 Aug-13-2023, 01:57 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020