[Tutor] File IO help

Kent Johnson kent37 at tds.net
Fri Oct 28 13:58:41 CEST 2005


Mike Haft wrote:
> Hello all,
>         I'm new to python but so far I have to say its a really good language
> 
> I've been having some trouble with File IO can anyone help? I've got the
> basics but my problem is that I have many files (one for each year of the
> last 100 years or so) that look like this:
> 
> MONTH  RAIN   AVTEMP  RAD  EVAP
> ****************************************
> 1      12.4    12.0    *   10
> 2      13.9    30.0    *   11
> 3
> 
> etc until month 12
> 
> So far all I know how to do in Python looks something like this:
> 
> def readInFile(inputName):
>     input = open(inputName, "r")
>     result = []
>     for line in input:
>         if line[:1] == "1":
>             fields = line.split()
>             data = fields[1] + fields[2] + fields[7]
>             result.append(data)
>     input.close()
>     return result

As you know this program returns data for the months that start with 1. Since you really want the data for all the months, you should just take out the conditional:

    for line in input:
        fields = line.split()
        data = fields[1] + fields[2] + fields[7]
        result.append(data)

Now result will have the data for all the months in order (though from your sample data there doesn't seem to be a field 7?).
> 
> Thats basically all I've been able to do but I need to write script that
> opens a file, reads the relevent data, stores that data and then closes
> the file and moves on to the next file repeating the action until all the
> files have been read. Then it needs to write a file with all the data it
> has collected but in a different format.

To do this you need a list of the files to read, and a loop that calls readInFile() for each file and stores the data somewhere. Then you need another function to write out the data to a new file.
> 
> If anyone can help I'd be really grateful. I hope I'm not asking too much
> of the list but I haven't found anything that says READ THIS BEFORE
> POSTING! on it to tell me otherwise.

Beginner questions are welcome. Have you read a tutorial or introductory book? It might give you some help with the basics. See this page for suggestions:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Kent



More information about the Tutor mailing list