[EMAIL PROTECTED] 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.
Since the lines that handle writing to the file aren't indented as far as the line that splits the data, they are not part of the loop. They are only executed once after the loop has completed, with town and latlong set to the values they got at the last iteration of the loop. It should look more like this: 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() -- http://mail.python.org/mailman/listinfo/python-list