繁体   English   中英

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

[英]How to skip empty lines in csv file when reading with python script?

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

使用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如果那是您的逻辑偏爱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM