[Tutor] read text file in zip archive, process, plot

Kent Johnson kent37 at tds.net
Sun Apr 15 15:43:53 CEST 2007


John W wrote:
> Kent and Alan: better?
> .j
> 
> import zipfile
> import os
> import pylab as P
> iFile = raw_input("Which file to process?")
> 
> def openarchive(filename):
>     """ open the cmet archive and read contents of file into memory """
>     z = zipfile.ZipFile(filename, "r")
>     for filename in z.namelist():
>         print filename
>         contents = z.read(filename)
>         data = contents.split('\n')
>         return data

This will just return the data of the first file in the zip, is that 
what you want? The return statement will exit from the loop. If there 
can be more than one file in the zip, you should call plotflight(data) 
within the loop instead of returning the data.

If you only want the first file, you could omit the loop and write
   filename = z.namelist()[0]

> def plotflight(data):
>     """ Plot flight data t vs. hPa with Pylab """
>     firstline = data[0].strip().split(' ')
>     stind = int(firstline[0])     
>     hdrline = stind - 1

You don't use hdrline

>     x = []
>     t = []
>     for l in data[stind:-1]:
>             l = l.split()  # Split on whitespace
>             tval = float(l[0])
>             t.append(tval)
>             xval = float(l[24])
>             x.append(xval)

I split out tval and xval for clarity but I would actually write this as
   t.append(float(l[0]))
and skip the temp variables.

>     #Create scatter plot using pylab function
>     P.scatter(t,x)
>     P.xlabel('time (s) after 00 UTC')
>     P.ylabel('Altitude (hPa)')
>     P.title('Flight elevation vs. Time')
>     P.grid(True)
>     #print out figure
>     if os.path.exists("flight_track.png"):
>      os.remove("flight_track.png")
>     P.savefig('flight_track')
>     P.close()
> 
> flightdata = openarchive(iFile)
> plotflight(flightdata)
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list