简体   繁体   English

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

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

I have a python script in which I want to read a csv file and then import this data into a postgres table. 我有一个python脚本,我想在其中读取一个csv文件,然后将此数据导入postgres表中。 Unfortunately the csv file is quite messy and has many blank lines. 不幸的是,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)

I want to skip stripping any row that has an empty cell for store_id and description - how would I do this? 我想跳过剥离任何具有store_id和description的空单元格的行-我该怎么做?

Use continue to skip the rest of the current loop, but keep on looping. 使用continue跳过当前循环的其余部分,但继续循环。 See https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops 参见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 returns false on a length 0 string, which will happen for an empty cell using the parsing above. not在长度为0的字符串上返回false,这将发生在使用上述解析的空单元格上。 Of course change the and to or if that's what your logic prefers. 当然,将and更改为or如果那是您的逻辑偏爱。

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

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