[Tutor] File IO and writing lists

Mike Haft m.haft at abdn.ac.uk
Fri Nov 4 21:54:39 CET 2005


"Carroll, Barry" <Barry.Carroll at psc.com> wrote:

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]]

Having doen that the code now looks like this:

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) < 13:
            print "Line too short", line
            continue
        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 "done"

It works fine so thanks for all the help on that, now just one more thing
and I can save myself about two months worth of copying and pasting.

The output from the above code (for one file) is:

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 VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA

Line too short
*************************************************************************************************************

[['RAIN', 'AVTEMP', 'EVAPW'], ['22.5', '0.3', '11.9'], ['16.1', '1.8',
'18.1'], ['16.4', '4.8', '36.8'], ['19.5', '5.9', '45.5'], ['36.1',
'13.2', '83.0'], ['36.0', '16.9', '105.7'], ['37.7', '18.2', '98.6'],
['29.3', '18.2', '97.9'], ['27.0', '14.8', '58.7'], ['57.6', '7.6',
'31.3'], ['23.4', '3.9', '19.1'], ['14.0', '0.7', '12.5']]
done
>>>

I don't know how to print these values in a new file sperated by new lines
and white space between the values (each line needs to be three values
corresponding to RAIN AVTEMP and EVAPW).
I know how to open a file and use out_file.write() type commands but not
how to write a list in the file. I tried the following:

print "opening file to write"
out_file = open("test.txt","w")
out_file.write(readSOMNETM(filename))
out_file.close()

But get the following error:

Traceback (most recent call last):
  File "C:\Python24\INProgress.py", line 23, in -toplevel-
    out_file.write(readSOMNETM(filename))
TypeError: argument 1 must be string or read-only character buffer, not list

How do you write a list to a file?

(Sorry for the long post)

Mike



More information about the Tutor mailing list