loop through each line in a text file

John Posner jjposner at optimum.net
Fri Feb 26 23:33:10 CET 2010

On 2/26/2010 4:21 PM, qtrimble wrote:
> fileIN = open(r"C:\testing.txt", "r")
> for line in fileIN:
>      year = line[3:7]
>      day = line[7:10]
>      print year, day
> This is good since i can get the year and day of year into a variable
> but I haven't gotten any further.

That's an excellent start. Here's another hint ...

There are two kinds of lines in your input file:

* lines that begin with "wer"
* all other lines

So you need an if-else section to process the lines in the input file:

   if line.startswith("wer"):
       # use the contents of *line* to assign values
       # to variables *year* and *day*
       # use the current values of *year* and *day*
       # to process the numbers extracted from *line*

Most likely, you'll also need these functions:

* split() -- chop a string into pieces
* int() -- string-to-integer conversion


More information about the Python-list mailing list