python - Writing sublists in a list of lists to separate text files -
i’m new python find myself working on travelling salesman problem multiple drivers. handle routes list of lists i’m having trouble getting results out in suitable .txt format. each sub-list represents locations driver visit, corresponds separate list of lat/long tuples. like:
driver_routes = [[0,5,3,0],[0,1,4,2,0]] lat_long =[(lat0,long0),(lat1,long1)...(latn,longn)]
what separate .txt file (named “driver(n)”) lists lat/long pairs driver visit.
when working single driver, following code worked fine me:
optimised_locs = open('optimisedroute.txt', 'w') x in driver_routes: to_write = ','.join(map(str, lat_long[x])) optimised_locs.write(to_write) optimised_locs.write("\n") optimised_locs.close()
so, took automated file naming code chris gregg here (printing out elements of list separate text files in python) , tried make iterating loop sublists:
num_drivers = 2 p = 0 while p < num_drivers: x in driver_routes[p]: f = open("driver"+str(p)+".txt","w") to_write = ','.join(map(str, lat_long[x])) print to_write # testing f.write(to_write) f.write("\n") f.close() print "break" # testing p += 1
the output on screen looks how expect , generate .txt files correct name. however, 1 tuple printed each file, not list expect. it’s simple can't see why while loop causes issue. appreciate suggestions , thank in advance.
you're overwriting contents of file f
on every iteration of for
loop because you're re-opening it. need modify code follows open file once per driver:
while p < num_drivers: f = open("driver"+str(p)+".txt","w") x in driver_routes[p]: to_write = ','.join(map(str, lat_long[x])) print to_write # testing f.write(to_write) f.write("\n") f.close() p += 1
note opening f
moved outside for
loop.
Comments
Post a Comment