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

vasilijepetkovic at yahoo.com vasilijepetkovic at yahoo.com
Wed Oct 26 04:49:04 EDT 2005


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




More information about the Python-list mailing list