0

Python 2.x Sample CSV input (I have many of these)

67.60.60.24, 1384, application/octet-stream,18/Feb/2015:00:00:50

Desired output:

insert into mytable (ip, bytes, type, timestamp) values ('67.60.60.24', 1384, 'application/octet-stream', '2015-02-18')

So far:

sqlTemplate = "insert into mytable (ip, bytes, type, timestamp) values ('{0}', {1}, '{2}', '{3}')

# lines contains many of the above sample input CSV lines

for line in lines:
  list = line.split(",")
  list = [elem.strip() for elem in list] # whitespace strip each element
  # Make sure len(list) == 4
  if len(list) != 4:
    continue
  sql = sqlTemplate.format(list) # how can i apply the list to the args?
  # todo: insert sql into DB
Totes McGoats
  • 111
  • 1
  • 3

1 Answers1

0

You can unpack a list using * operator.

In your case

sql = sqlTemplate.format(*list)

If your list is ["a", "b", "c"], this code is the same of:

sql = sqlTemplate.format("a", "b", "c")

But, of course, you now can call the format function with different number of parameters

Yuri Malheiros
  • 1,400
  • 10
  • 16