我在一个类中有这个功能
def readInput(self, inFile):
with open(inFile, "r") as file:
for line in file:
if (line.split()[0] == "Ks"):
nextLine = next(file)
self.Ks = nextLine.split()[0]
self.thetaS = nextLine.split()[1]
self.thetaR = nextLine.split()[2]
self.alpha = nextLine.split()[3]
self.lamb = nextLine.split()[4]
self.n = nextLine.split()[5]
它基本上是在输入文件("Ks"
)中搜索模式(inFile
),以将inFile
下一行的变量值存储在实例变量中。
代码中有很多重复,我认为可以用一种聪明的(而且更短的)方式来写。
有什么想法吗?
输入文件如下:
### Soil hydraulic properties. Units: m, d
Ks ThetaS ThetaR alpha lambda n
0.128 0.01 0.42 0.84 -1.497 1.441
答案 0 :(得分:5)
使用元组拆包:
self.Ks, self.thetaS, self.thetaR, self.alpha, self.lamb, self.n = nextLine.split()
答案 1 :(得分:2)
另一种可能性是使用标准CSV package。
import csv
with open('testdata.csv', newline='') as file:
csvreader = csv.reader(file, delimiter=' ', skipinitialspace=True)
next(csvreader) # omit the comment at start of file
header = next(csvreader)
for row in csvreader:
print(', '.join(row))