Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.