[Numpy-discussion] Reading footer lines

Daπid davidmenhur@gmail....
Tue Aug 13 08:01:34 CDT 2013

On 13 August 2013 14:20, Resmi <l.resmi@gmail.com> wrote:
> As a workaround, I've tried using os.system along with grep. And I get the
> following output :
>>>> os.system("grep -e 'tx' 'data.dat' ")
>  ## tx =    2023.06
> 0
> Why is there a 0 in the output? The file has no blank lines.

That 0 corresponds to the exit status of os.system, as there were no
errors, it returns a 0.

My idea would be to read the file and store it into a StringIO. That
can be fed to np.loadtxt to extract the numbers, and look for your
number. My (untested) attempt:

import StringIO

with datafile open as f:
... raw_data = StringIO.StringIO()
... raw_data.write(f.read())

data = np.loadfromtxt(raw_data)
numbers = [float(line.split['='][1].strip()) for line in
raw_data.readlines() if line[0] == '#']

If there is only one number there and it is after all the data, you
could skip them all. From the shape of data you know there are N lines
of data:

for _ in range(N):
... raw_data.readline()
while True:
... line = raw_data.readline()
... if line[0] == '#':
...... number = float(line.split['='][1].strip())
...... break

Alternatively, you could also use seek to put the pointer a certain
distance from the end of the file and start from there, but this could
cause problems in Windows.


More information about the NumPy-Discussion mailing list