[英]How to read text file line by line and save values into variables in python
[英]How to read a file in python and ignore the comment part to save values to variables?
我有这个档案
-200 200 # Domain size in X direction in meter
-200 200 # Domain size in Y direction in meter
0.0 200.0 # Domain size in Z direction in meter
25 25 25 # Number of nodes in X, Y and Z direction
1 # Number of measurments
-0.0 0.0 5.0
3.44e-12
我想使用python读取此内容,并将值仅保存到某些变量。 我试过了
with open("input.dat") as f:
for line in f:
line = line.partition('#')[0]
line = line.rstrip()
fields = line.strip().split()
print(fields[0], fields[1], fields[2])
将它们分成字段,但不起作用,并返回带有错误的空字段
IndexError: list index out of range
如果我尝试访问“字段”
提前致谢
为了避免在访问fields[1]
或fields[2]
IndexError
,可以设置一个条件来检查它们是否存在。 如果不是,则输入默认值进行打印(例如0)。
if len(fields) == 0:
print ("0","0","0")
elif len(fields) == 1:
print (fields[0], "0", "0")
elif len(fields) == 2:
print (fields[0], fields[1], "0")
else:
print (fields[0], fields[1], fields[2])
用以下两个语句替换代码的print语句:
for val in fields:
print (val, end=' ')
问题在于某些行中的值少于三个。 因此,fields [2]将产生索引错误。
基本问题是,当您的某些行只有一个字段时,您试图打印(或保存到变量)三个字段。
根据数据块中的注释,听起来好像数据块中的每一行数据的解释方式都不相同。 如果是这种情况,您实际上应该以不同的方式解析每一行,而不是尝试使用相同的代码来解析每一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.