使用python脚本阅读时如何跳过csv文件中的空行?

时间:2014-08-07 21:40:07

标签: python postgresql csv

我有一个python脚本,我想在其中读取一个csv文件,然后将这些数据导入到postgres表中。不幸的是,csv文件非常混乱并且有很多空行。

arg = {
     'date': date,
     'store_id': row[0].strip(),
     'price': row[1].strip(),
     'description': row[2].strip()
   }

cur.execute(
 """INSERT INTO 
    "Inventory"("date","store_id","price","description")
    select %(date)s, 
    %(store_id)s, 
    %(price)s, 
    %(description)s
          ;""", arg)

我想跳过剥离任何具有store_id和描述的空单元格的行 - 我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用continue跳过当前循环的其余部分,但继续循环。见https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

for line in open(filename):
    row = line[:-1].split(",")
    arg = {'date': date,
           'store_id': row[0].strip(),
           'price': row[1].strip(),
           'description': row[2].strip()}
    if not arg['store_id'] and not arg['description']:
        continue
    # cur.execute bit here...

not在长度为0的字符串上返回false,对于使用上述解析的空单元格,将发生这种情况。当然,如果您的逻辑偏好,请将and更改为or

相关问题