while1: line=file.readline().strip() print line ifnot line: break count=cur.execute("select cus.customer_state,cus.name from crm_customer_hotel as hotel join crm_customer as cus on hotel.customer_serial_number=cus.serial_number where hotel.hotel_seq='%s'" % line) result = cur.fetchone() print result if result: outfile.write(str(result[0])+" "+result[1]) outfile.write('\n') cur.close() file.close() outfile.close()