Python 2.x. 样本CSV输入(我有很多这些)
67.60.60.24, 1384, application/octet-stream,18/Feb/2015:00:00:50
期望的输出:
insert into mytable (ip, bytes, type, timestamp) values ('67.60.60.24', 1384, 'application/octet-stream', '2015-02-18')
到目前为止:
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
答案 0 :(得分:0)
您可以使用*运算符解压缩列表。
在你的情况下
sql = sqlTemplate.format(*list)
如果您的列表是[" a"," b"," c"],则此代码与以下内容相同:
sql = sqlTemplate.format("a", "b", "c")
但是,当然,您现在可以使用不同数量的参数调用格式函数