如何从外部txt fi获取变量值

2024-09-29 01:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个txt文件:

#internal radius of the stator
r_int_stat=0.34
#axial coordinate of the beginning of the rotor
rotor_in=0.1289
#axial coordinate of the end of the rotor
rotor_end=0.173
#internal radius of the rotor
r_int_rot=0.32
#axial coordinate of the end of the domain
end=0.306
#external radius
r_ext=0.4

我想创建一个Python脚本来调用这个txt文件并使用这些变量。我有这个Python代码:

file=open("testfile.dat","w")
file.write("Header\n")
file.write("\n")
if curve==1:
     file.write("XYZ polyline\n")
     file.write("2\n")
     #the z coordinate remains always zero because I have an axysimmetric mesh
     file.write('0 '+str(r_int_stat)+' 0\n')
     file.write(str(rotor_in)+' '+str(r_int_stat)+' 0\n')
     file.write('\n')
     file.write('XYZ polyline\n')
     file.write('2\n')
     file.write(str(rotor_in)+' '+str(r_int_stat)+' 0\n')
     file.write(str(rotor_end)+' '+str(r_int_rot)+' 0\n')
     file.write('\n')
     file.write('XYZ polyline\n')
     file.write('2\n')
     file.write(str(rotor_end)+' '+str(r_int_rot)+' 0\n')
     file.write(str(end)+' '+str(r_int_rot)+' 0\n')
     file.write('\n')
     file.write('XYZ polyline\n')
     file.write('2\n')
     file.write(str(end)+' '+str(r_int_rot)+' 0\n')
     file.write(str(end)+' '+str(r_ext)+' 0\n')
     file.write('\n')
     file.write('XYZ polyline\n')
     file.write('2\n')
     file.write(str(end)+' '+str(r_ext)+' 0\n')
     file.write('0 '+str(r_ext)+' 0\n')
     file.write('\n')
     file.write('XYZ polyline\n')
     file.write('2\n')
     file.write('0 '+str(r_ext)+' 0\n')
     file.write('0 '+str(r_int_stat)+' 0\n')

else:
     file.write("XYZ cspline\n")
     file.write("5\n")


file.close()

我希望这个Python代码从txt文件中获取变量的值,因为我需要修改这些变量,所以从外部txt文件中获取变量更容易

谢谢你的帮助


Tags: 文件ofthetxtextstatfilewrite
1条回答
网友
1楼 · 发布于 2024-09-29 01:30:23

按照迪奇先生的建议,使用Configparser(如果他回答了,请告诉我,我会删除这个答案。)

首先在文件的开头放一行来修改这个文件

[parameters]
#internal radius of the stator
r_int_stat=0.34
#axial coordinate of the beginning of the rotor
rotor_in=0.1289
#axial coordinate of the end of the rotor
rotor_end=0.173
#internal radius of the rotor
r_int_rot=0.32
#axial coordinate of the end of the domain
end=0.306
#external radius
r_ext=0.4

下面的Python代码建议如何提取其内容

打开配置文件,询问它的节是什么(在您的示例中只有一节),获取该节内容的字典,然后显示字典

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('testfile.dat')
['testfile.dat']
>>> config.sections()
['parameters']
>>> d = config['parameters']
>>> for key, value in d.items():
...     key, value
...     
('r_int_stat', '0.34')
('rotor_in', '0.1289')
('rotor_end', '0.173')
('r_int_rot', '0.32')
('end', '0.306')
('r_ext', '0.4')

相关问题 更多 >