[Tutor] read text file in zip archive, process, plot
Kent Johnson
kent37 at tds.net
Sun Apr 15 13:23:19 CEST 2007
Washakie Wyoming wrote:
> Greetings all!
>
> I'm including here a first python program! Very nice. It's written to
> read in a text file which resides in a .zip archive, extract two fields
> and plot them. It uses some bits from pylab for the plotting.
>
> I'm writing to ask for ways to improve it. I feel like the writing and
> reading from 'jnk' files is definitely a hack! Any suggestions? I would
> be greatly appreciative of anyone provided comments on how to more
> efficiently tackle this problem. (NOTE: this is not a school
> assignment... just some side learning out of interest in what seems to
> be a great language!).
>
> Thanks!
>
> Here's my program (a zip is attached - if that's allowed???):
>
> import zipfile
> import os
> import pylab as P
>
> z = zipfile.ZipFile("flight_data.zip", "r")
> for filename in z.namelist():
> print filename
> contents = z.read(filename)
> f = open('jnk','w')
> f.write(contents)
> f.close()
> print "file closed, now reading"
> #now open files to process
> f = open('jnk','r')
> fn = open('newjnk','w')
> data = f.readlines()
Alan has shown you a better way to do this.
> firstline = data[0].strip().split(' ')
> stind = int(firstline[0])
> hdrline = stind - 1
> #print data[stind:len(data)]
> for l in data[stind:len(data)]:
You don't need the end index when it is the length of the data:
for l in data[stind:]:
> #l = l.replace(' ',',')
> fn.writelines(l)
> f.close()
> fn.close()
> #print 'file closed now'
>
> jnk2 = P.load('newjnk')
> t = jnk2[:,0]
> x = jnk2[:,24]
It looks like you are using newjnk just as a way to get P.load() to
parse the data for you. You can do this yourself with something like
x = []
t = []
for l in data[stind:]:
l = l.split() # Split on whitespace
tval = float(l[0])
t.append(tval)
xval = float(l[24])
x.append(xval)
Kent
More information about the Tutor
mailing list