[Tutor] File IO

Carroll, Barry Barry.Carroll at psc.com
Fri Nov 4 00:47:05 CET 2005


Mike:

I see two issues here:

First, do you really want to apply your field selection logic to ALL the
lines in each file?  It seems to me that the first five lines of the file
are header information that you want to ignore.  If so, and if all the files
have the same format, you can use a loop to throw away the first five lines
of the input and start collecting your data on line #6. Another possibility
would be to check each line and throw it away if fields[1] cannot be
converted into a number.  

Second, your current logic is assembling the data from each line into a
string.  Is that what you want?  I'm guessing you want to extract the three
fields into a three element list.  If so, you need to turn the three strings
(fields[1], fields[2] and fields[3]) back into list elements.  Do this by
placing them in square brackets separated by commas:

     data = [fields[1], fields[2], fields[7]]



> ------------------------------
> Date: Thu, 3 Nov 2005 22:10:02 -0000 (GMT)
> From: "Mike Haft" <m.haft at abdn.ac.uk>
> Subject: Re: [Tutor] File IO
> To: "bob" <bgailer at alum.rpi.edu>
> Cc: tutor at python.org
> Message-ID: <1997.84.43.99.200.1131055802.squirrel at www.abdn.ac.uk>
> Content-Type: text/plain;charset=iso-8859-1
> 
> I did that and got this:
> 
> Here goes
> Enter filename:
> Name:LAU73M.MET
> Line too short Monthly Weather Data, LAU73M.MET, converted from:
> 
> Line too short BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR
> 01/01/1973-31/12/1973
> 
> Line too short
> **********************************************************************
> 
> ['DEWPCALCULATEDHUMID', 'RAINAVTEMPEVAPW', '22.50.311.9', '16.11.818.1',
> '16.44.836.8', '19.55.945.5', '36.113.283.0', '36.016.9105.7',
> '37.718.298.6', '29.318.297.9', '27.014.858.7', '57.67.631.3',
> '23.43.919.1', '14.00.712.5']
> might work
> 
> Its worth pointing out that there are more than eight fields in my actual
> files, I'm using a shorter version just to test stuff on. Actual fields
> are:
> 
> MONTH    RAIN  AVTEMP     S10        RAD          SUN    WIND   EVAPW
> EVAPG   EVAPS   HUMID     VAP    DEWP
> 
> There are 13 so I'll have a play with that for the moment.
> 
> Thanks for the help
> 
> Mike
> 
> 
> > At 01:34 PM 11/3/2005, Michael Haft wrote:
> >>Hello,
> >>      I tried the following code:
> >>
> >>def readSOMNETM(inputName):
> >>     input = open(inputName, "r")
> >>     result = []
> >>     for line in input:
> >>         fields = line.split()
> >
> >            # add this; it will show you what line(s) have less than 8
> > fields
> >            if len(fields) < 8:
> >                print "Line too short", line
> >                continue
> >
> >>         data = fields[1] + fields[2] + fields[7]
> >>         result.append(data)
> >>     input.close()



More information about the Tutor mailing list