简体   繁体   中英

How do I write text lines to file with variables to a file?

I am trying to automate writing a large Silvaco ATLAS (a TCAD software) script with varying values of variables in it through python. So I am trying to write ATLAS code lines to a file but I want to use key/variable values from a dictionary that I have generated in my python code. Any better way to do this?

Let's say the dict in my python looks like,

    variable_dict = {'length':22, 'height': 200, 'width':10}

(A similar dict but with a lot more keys) so I was going to write the ATLAS code as follows:

    atlas_code = ''' x=%length
                     y=%height
                     z=%width
             '''

(a similar ATLAS code but with a lot more lines of code and lot more variables from the variable_dict)

and the write it to a file, like

    f.write(atlas_code)

I expect the written ATLAS file to look like

    #atlas_code.in
    x=22
    y=200
    z=10

You can use Template like below:

import string
content = string.Template('x=$length\ny=$height\nz=$width')
f.write(content.substitute(length=variable_dict['length'], height=variable_dict['height'], width=variable_dict['width']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM