Considering migrating to Python from Visual Basic 6 for engineering applications

Roel Schroeven roel at roelschroeven.net
Sat Feb 20 17:28:40 EST 2016


wrong.address.1 at gmail.com schreef op 2016-02-19 11:47:
> Thanks. The data I will often have to read from text files could read like
> 
> 2 12.657823 0.1823467E-04 114 0
> 3 4 5 9 11
> "Lower"
> 278.15
> 
> Is it straightforward to read this, or does one have to read one character at a time and then figure out what the numbers are?

The question is: what is known about the format of the data? Is it 
fixed, or does the code need to be smart enough to be able to deal with 
varying formats?

If we can assume that there are 4 lines, of which the first line 
contains floating point numbers, the second contains integers, the third 
contains one string and the fourth contains one floating point number, 
it's pretty easy. For example:

def readinput(filename):
     with open(filename, 'rt') as f:
         lines = f.readlines()
     line0 = [float(part) for part in lines[0].split()]
     line1 = [int(part) for part in lines[1].split()]
     line2 = lines[2].strip()[1:-1]
     line3 = float(lines[3])
     return line0, line1, line2, line3

line0, line1, line2, line3 = readinput('input.txt')
print(line0)
print(line1)
print(line2)
print(line3)

Output:

[2.0, 12.657823, 1.823467e-05, 114.0, 0.0]
[3, 4, 5, 9, 11]
Lower
278.15

This basically splits the two first line by whitespace, then converts 
each part (or the whole line in case of the last two lines) into the 
desired data type.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

Roel Schroeven



More information about the Python-list mailing list