【问题标题】:How to skip empty lines in csv file when reading with python script?使用python脚本阅读时如何跳过csv文件中的空行?
【发布时间】:2014-08-07 21:40:06
【问题描述】:

我有一个 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 和描述的空单元格的任何行 - 我该怎么做?

【问题讨论】:

    标签: python postgresql csv


    【解决方案1】:

    使用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

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      相关资源
      最近更新 更多