[Tutor] File IO

Colin J. Williams cjw at sympatico.ca
Fri Nov 4 01:47:54 CET 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()
>        data = fields[1] + fields[2] + fields[7]
>        result.append(data)
>    input.close()
>    return result
>
>
>print "Here goes"
>print "Enter filename:"
>filename = raw_input("Name:")
>print readSOMNETM(filename)
>print "might work"
>
>on  a file that lookes like this:
>
>Monthly Weather Data, LAU73M.MET, converted from:
>BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973
>VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA
>MONTH	RAIN	AVTEMP	S10	RAD	SUN	WIND	EVAPW
>**************************************************************
>1	22.5	0.3	*	54.6	15.1	*	11.9
>2	16.1	1.8	*	110	51.1	*	18.1
>3	16.4	4.8	*	227.5	94.5	*	36.8
>4	19.5	5.9	*	286.3	89	*	45.5
>5	36.1	13.2	*	448.5	164.6	*	83
>6	36	16.9	*	525.7	208.8	*	105.7
>7	37.7	18.2	*	459.7	165.4	*	98.6
>8	29.3	18.2	*	463.8	206.8	*	97.9
>9	27	14.8	*	277.5	119.5	*	58.7
>10	57.6	7.6	*	158.7	72.2	*	31.3
>11	23.4	3.9	*	98.3	75.6	*	19.1
>12	14	0.7	*	55.5	38	*	12.5
>
>
>And recieved the following error:
>
>Traceback (most recent call last):
>  File "C:\Python24\INProgress.py", line 15, in -toplevel-
>    print readSOMNETM(filename)
>  File "C:\Python24\INProgress.py", line 6, in readSOMNETM
>    data = fields[1] + fields[2] + fields[7]
>IndexError: list index out of range
>
>Essentially I'm trying to write a bit of code that can take any of the
>fields in the above data i.e. rain temp evap for each month for a hundred
>or so files like this one and spit out a file at the end that has the data
>in a different format.
>
>Any help would be very much appreciated I need to get this done by the end
>of next week
>
>Thanks
>
>Mike
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
My guess is that you have a line, perhaps the last one in the file, 
which does not end with '\n'.

You might try:

def readSOMNETM(inputName):
    input = open(inputName, "r")
    result = []
    for line in input:
        fields = line.split()
	try:
          data = fields[1] + fields[2] + fields[7]
        except:
          print repr(line)
          print fields
          raise ValueError
        result.append(data)
    input.close()
    return result


Colin W.




More information about the Tutor mailing list