如何在用Python读取CSV文件时跳过空行?

0 投票
1 回答
1387 浏览
提问于 2025-04-18 16:28

我有一个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和description这两列中有空白单元格的行,我该怎么做呢?

1 个回答

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的字符串时会返回假值,这种情况在上面的解析中会出现在空单元格里。当然,如果你的逻辑需要,可以把 and 改成 or

撰写回答