0

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

2 Answers 2

5

Using tuple unpacking:

self.Ks, self.thetaS, self.thetaR, self.alpha, self.lamb, self.n = nextLine.split()
Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.