I have a .wbjn file (ANSYS workbench journal file) which is a python file in which I have to replace certain variables. Eg.
parameter_1 = variable_1
parameter_2 = variable_2
.
.
parameter_n = variable_n
I have to replace the variables_1....n with a list of values.
So I created a mapping dictionary and iterated over it to replace the values. But the values are not getting replaced with the code I wrote;
map_dict = {'variable_1':'20','variable_2':'15'}
handle = open("filename.wbjn","r ")
for l in handle:
for k,v in map_dict.items():
l = l.replace(k,str(v))
handle.write(l)
handle.close()
The file has several other lines which do not need to be modified. What is the problem here and how do I solve it.
Thanks
CodePudding user response:
You could use fileinput
package which enables to edit files in-place
. Please find the draft that you can experiment with:
Example file.txt:
parameter_1 = variable_1
parameter_n = variable_n
parameter_4 = variable_4
parameter_k = variable_k
Script
from fileinput import FileInput
map_dict = {'variable_1': '20', 'variable_4': '15'}
with FileInput('file.txt', inplace=True) as file:
for line in file:
line = line.strip()
parts = line.split('=')
parameter = parts[0].strip()
variable = parts[1].strip()
if variable in map_dict:
print(f"{parameter} = {map_dict[variable]}")
else:
print(line)
file.txt after execution
parameter_1 = 20
parameter_k = variable_n
parameter_4 = 15
parameter_k = variable_k
Please note that print
function does not show in the script output but writes lines into the file.
For details please find fileinput documentation
CodePudding user response:
It looks like, already after reading the first line, it jumps at the end of the fileto write, and after that there is no other line. Mine is not the most elegant solution, but it works:
map_dict = {"variable_1": "20", "variable_2": "15"}
handle = open("filename.wbjn", "r ")
processed = []
for l in handle:
for k, v in map_dict.items():
l = l.replace(k, str(v))
processed.append(l)
handle.seek(0)
handle.write("".join(processed))
handle.truncate()
handle.close()
CodePudding user response:
This code may help you.
map_dict = {'variable_1':'20','variable_2':'15'}
with open("filename.wbjn","r ") as handle:
handle_data = handle.readlines()
for a in range(len(handle_data)):
for k,v in map_dict.items():
handle_data[a] = handle_data[a].replace(k,str(v))
handle.seek(0)
handle.write('')
handle.writelines(handle_data)