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

Iain King iainking at gmail.com
Wed Oct 26 05:12:16 EDT 2005


vasilijepetkovic at yahoo.com wrote:
> Hello All,
>
> I have a problem with the program that should generate x number of txt
> files (x is the number of records in the file datafile.txt).
>
> 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.
>
> The program is as follows:
> ====================================
> #!  python
>
> HEADER = "This page displays longitude-latitude information"
> SUBHEADER = "City"
>
> for line in open("datafile.txt"):
>
>
>     town, latlong = line.split('\t')
>
> f = open(town + ".txt", "w+")
>
> f.write(HEADER + "\n")
> f.write(SUBHEADER + ": " + town + "\n")
> f.write("LAT/LONG" + ": " + latlong + "\n")
> f.close()
>
>
> # end
> ====================================
>
>
>
>
> The datafile.txt is as follows (tab separated columns):
> ====================================
>
> NYC	1111-2222
> Lima	3333-4444
> Rome	5555-6666
>
> ====================================
>
> Once executed, the program will create a single file (named Rome.txt)
> and it would not create files NYC.txt and Lima.txt as I would expect it
> to do.
>
> I'd appreciate if you can pinpoint my error.
> 
> Best, 
> 
> Vasa

Did you try indenting the last five lines?

Iain




More information about the Python-list mailing list