> Tim, in your code: > > filename = 'foo.tab' > for i, line in enumerate(open(filename)): > if i == 0: continue # skip the header row > (fieldname1, fieldname2, fieldname3 ... > ) = line.rstrip('\n').split('\t') > cursor.execute(""" > INSERT INTO app_foo > (f1, f3, f2) > VALUES > (%s, %s, %s) > """, (fieldname1, fieldname3, fieldname2) > ) > > f1, f2, and f3 would be my "first", "last", and "phone", and the > fieldname1 to fieldname3 would be the data from "first", "last", and > "phone"?
The (fieldname1, fieldname2, fieldname3) assignment at the top pulls the values from the line into those particular variables. In your case you might want to write the above as filename = 'foo.tab' for i, line in enumerate(open(filename)): if i == 0: continue # skip the header row # these are the columns in the given row (last_name, first_name, phonenumber, email, dob, ... ) = line.rstrip('\n').split('\t') cursor.execute(""" INSERT INTO app_foo (first, last, phone) VALUES (%s, %s, %s) """, (first_name, last_name, phonenumber) ) If you happen to know the order of the columns in your tab-separated file, and they don't need any further manipulation (such as changing case, stripping whitespace, calculating or dropping columns, etc), you can even simplify the above to for i, line in enumerate(open(filename)): if i == 0: continue # skip the header row # assumes the line is "first\tlast\tphone" row = line.rstrip('\n').split('\t') cursor.execute(""" INSERT INTO app_foo (first, last, phone) VALUES (%s, %s, %s) """, row ) If you know your files aren't all that big (swamping memory), you can even get grotesque with it, doing things like cursor.executemany(""" INSERT INTO app_foo (first, last, phone) VALUES (%s, %s, %s) """, [row.rstrip('\n').split('\t') for i, row in enumerate(open(filename)) if i > 0]) Huzzah for list comprehensions ;) If executemany() supports iterators rather than requiring lists, you could omit the square brackets, and it wouldn't matter how large your file-size was. The executemany() call is considerably more efficient if you have large volumes of preparable statements. -tim --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---