简体   繁体   English

如何使用变量将文本行写入文件?

[英]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. 我试图通过python自动编写一个大型的Silvaco ATLAS(一个TCAD软件)脚本,其中包含不同的变量值。 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. 所以我试图将ATLAS代码行写入文件,但我想使用我在python代码中生成的字典中的键/变量值。 Any better way to do this? 有更好的方法吗?

Let's say the dict in my python looks like, 让我们说我的python中的字典看起来像,

    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: (一个类似的dict,但有更多的键)所以我打算编写ATLAS代码如下:

    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) (类似的ATLAS代码,但代码行更多,变量更多来自variable_dict)

and the write it to a file, like 并将其写入文件,如

    f.write(atlas_code)

I expect the written ATLAS file to look like 我希望写入的ATLAS文件看起来像

    #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']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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