Reputation: 128
I have this function inside a class
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]
It basically search for a pattern ("Ks"
) inside an input file (inFile
) to store variable values from the next line of inFile
inside instance variables.
There is a lot of repetition in the code and I think it's possible to write that in a clever (and shorter) way.
Any ideas?
The input file looks like this:
### Soil hydraulic properties. Units: m, d
Ks ThetaS ThetaR alpha lambda n
0.128 0.01 0.42 0.84 -1.497 1.441
Upvotes: 0
Views: 45
Reputation: 1628
Another possibility is to use the standard 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))
Upvotes: 2
Reputation: 36023
Using tuple unpacking:
self.Ks, self.thetaS, self.thetaR, self.alpha, self.lamb, self.n = nextLine.split()
Upvotes: 5