简体   繁体   中英

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. Unfortunately the csv file is quite messy and has many blank lines.

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?

Use continue to skip the rest of the current loop, but keep on looping. See 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. Of course change the and to or if that's what your logic prefers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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