![](/img/trans.png)
[英]How do I write lines to a text file easily if I have a dictionary with the key of the line and contents being the text?
[英]How do I write text lines to file with variables to a file?
我試圖通過python自動編寫一個大型的Silvaco ATLAS(一個TCAD軟件)腳本,其中包含不同的變量值。 所以我試圖將ATLAS代碼行寫入文件,但我想使用我在python代碼中生成的字典中的鍵/變量值。 有更好的方法嗎?
讓我們說我的python中的字典看起來像,
variable_dict = {'length':22, 'height': 200, 'width':10}
(一個類似的dict,但有更多的鍵)所以我打算編寫ATLAS代碼如下:
atlas_code = ''' x=%length
y=%height
z=%width
'''
(類似的ATLAS代碼,但代碼行更多,變量更多來自variable_dict)
並將其寫入文件,如
f.write(atlas_code)
我希望寫入的ATLAS文件看起來像
#atlas_code.in
x=22
y=200
z=10
你可以使用如下的模板:
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.