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
  What does .flush do? How can I change this to write to the file? Pedroski55 3 237 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 454 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 1,553 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,479 Nov-09-2023, 10:56 AM
Last Post: mg24
  Need to replace a string with a file (HTML file) tester_V 1 778 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  doing string split with 2 or more split characters Skaperen 22 2,563 Aug-13-2023, 01:57 AM
Last Post: Skaperen
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,162 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  Replacing String Variable with a new String Name kevv11 2 794 Jul-29-2023, 12:03 PM
Last Post: snippsat
  How to "tee" (=split) output to screen and into file? pstein 6 1,409 Jun-24-2023, 08:00 AM
Last Post: Gribouillis
  How do I read and write a binary file in Python? blackears 6 6,721 Jun-06-2023, 06:37 PM
Last Post: rajeshgk

Forum Jump:

User Panel Messages

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