Looping Problem (Generating files - only the last record generates a file)

Peter Otten __peter__ at web.de
Wed Oct 26 11:30:17 CEST 2005


vasilijepetkovic at yahoo.com wrote:

> Once I execute the program (see below) only one file (instead of x
> files) is created. The file created is based on the last record in
> datafile.txt.

> #!  python
> 
> HEADER = "This page displays longitude-latitude information"
> SUBHEADER = "City"
> 
> for line in open("datafile.txt"):
> 
> 
>     town, latlong = line.split('\t')
 
In Python whitespace is significant. For the following to be executed in the
for-loop it has to be indented to the same level as the line above. 

> f = open(town + ".txt", "w+")
> 
> f.write(HEADER + "\n")
> f.write(SUBHEADER + ": " + town + "\n")
> f.write("LAT/LONG" + ": " + latlong + "\n")
> f.close()
> 
> 
> # end
> ====================================

The effect of aligning it with the for-statement is that it is executed only
once /after/ the loop has run to completion. At that point town and latlong
are still bound to the values they were assigned in the last iteration
(with an empty datafile.txt the loop would never be executed and you would
get a NameError).

Peter




More information about the Python-list mailing list