2

I need to read in a CSV file, from Excel, whose rows may be an arbitrary length.

The problem is the python retains these blank entries, but need to delete them for a future algorithm. Below is the output, I don't want the blank entries.

     ['5', '1', '5', '10', '4', '']
     ['3', '1', '5', '10', '2', '']
     ['6', '1', '5', '10', '5', '2']
     ['9', '10', '5', '10', '7', '']
     ['8', '5', '5', '10', '7', '']
     ['1', '1', '5', '10', '', '']
     ['2', '1', '5', '10', '1', '']
     ['7', '1', '5', '10', '6', '4']
     ['4', '1', '5', '10', '3', '1']

3 Answers 3

3

Here's a list comprehension integrated with the csv library:

import csv

with open('input.csv') as in_file:
    reader = csv.reader(in_file)
    result = [[item for item in row if item != ''] for row in reader]

print result
Sign up to request clarification or add additional context in comments.

Comments

1

This is about as verbose a function as I could write to do what you want. There are certainly slicker ways.

def remove_blanks(a_list):
    new_list = []
    for item in a_list:
        if item != "":
            new_list.append(item)
    return new_list

Comments

1

List comprehension version:

a = ['5', '1', '5', '10', '4', '']

[x for x in a if x != '']
Out[19]: ['5', '1', '5', '10', '4']

You may be better served by filtering at the csv read step instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.