Im making a program that parses .m file into .h file with rearanging some stuff in different order. Im basically new to Python, but I know other language. Program code is:
with open('D:\\\toolchain\Simulink\data\\application_parameters_data.m','r') as InputFile:
for j in InputFile:
for k in range(2): InputFile.readline()
with open('D:\\\toolchain\Connector\ConDataGenerated.h', 'w') as file1:
t1 = Template('$datatype $name $initValue $comment')
for i in InputFile:
file1.write("\n")
Type = [name.strip() for name in i.split(';\n')[0].split(',')]
file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))
I need to change it contence divided by , between elements and ; between lines accordingly. Example of input code:
'ManCtrlInputShaftSpeedSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeedPar', 0, [0 1], '', 'comment', 'single';
'ManCtrlInputShaftSpeed1Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeed1Par', 0, [0 1], '', 'comment', 'single';
'ManCtrlInputShaftSpeed2Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeed2Par', 0, [0 1], '', 'comment', 'single';
'ManCtrlOutputShaftSpeedSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlOutputShaftSpeedPar', 0, [0 1], '', 'comment', 'single';
'ManCtrlOutputShaftSpeedDirnSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlOutputShaftSpeedDirnPar', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlMeasPositionS1Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlMeasPositionS1Par', 0, [0 1], '', 'comment', 'single';
Here's the thing. Script works fine until it hits the space between strings or something that it doesnt recognise, or, it works with writing only first element of string to new file, in that case it iterates through strings without problems. I think it somehow connected to compiler telling me next:
Traceback (most recent call last):
File "D:\\StringTemplate.py", line 16, in <module>
file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))
IndexError: list index out of range
even though file creates with this problems. example of output code:
'uint16' 'ManCtrlInputShaftSpeedSwt' 0 'comment'
'single' 'ManCtrlInputShaftSpeedPar' 0 'comment'
'uint16' 'ManCtrlInputShaftSpeed1Swt' 0 'comment'
'single' 'ManCtrlInputShaftSpeed1Par' 0 'comment'
'uint16' 'ManCtrlInputShaftSpeed2Swt' 0 'comment'
'single' 'ManCtrlInputShaftSpeed2Par' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedSwt' 0 'comment'
'single' 'ManCtrlOutputShaftSpeedPar' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedDirnSwt' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedDirnPar' 0 'comment'
What should I do?
CodePudding user response:
You can add a condition to check if the line has a length of 5 / if it's not empty, something like:
Type = [name.strip() for name in i.split(';\n')[0].split(',')]
if len(Type) > 5:
file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))