user9601710
user9601710

Reputation:

How to read CSV with column with more than one element in Python

I have the following CSV file:

id;name;duration;predecessors;
10;A;7;;
20;B;10;10;
25;B2;3;10;
30;C;5;10;
40;D;5;20,30, 25;

That is, the last row, in the fourth column I have three elements (20,30,25) separated by comma.

I have the following code:

csv_file = open(path_to_csv, 'r')
csv_file_reader = csv.reader(csv_file, delimiter=',')

first_row = True
for row in csv_file_reader :

    if not first_row:
        print(row)

    else :
        first_row = False

but I get a weird output:

['10;A;7;;']
['20;B;10;10;']
['25;B2;3;10;']
['30;C;5;10;']
['40;D;5;20', '30', ' 25;']

Any ideas? Thanks in advance

Upvotes: 0

Views: 141

Answers (2)

hygull
hygull

Reputation: 8740

@Antonio, I appreciate the above answer. As we know CSV is a file with comma separated values and Python's csv module works based on this, by default.

✓ No problem, you can still read from it without using csv module.

✓ Based on your provided input in problem I have written another simple solution without using any Python module to read CSVs (it's ok for simple tasks).

Please read, try and comment if you are not satisfied with the code or if it fails for some of your test cases.I will modify and make it workable.

» Data.csv

id;name;duration;predecessors;
10;A;7;;
20;B;10;10;
25;B2;3;10;
30;C;5;10;
40;D;5;20,30, 25;

Now, have a look at the below code (that finds and prints all the lines with 4th column having more than one elements):

with open ("Data.csv") as csv_file:
    for line in csv_file.readlines()[1:]:
        arr = line.strip().split(";")
        if len(arr[3].split(",") )> 1:
            print(line) # 40;D;5;20,30, 25;

Upvotes: 0

hunteke
hunteke

Reputation: 3716

You have specified CSV in your description, which stands for Comma Separated Values. However, your data uses semicolons.

Consider specifying the delimiter as ; for the CSV library:

with open(path_to_csv, 'r') as csv_file:
    csv_file_reader = csv.reader(csv_file, delimiter=';')

    ...

And while we're here, note the change to using the with statement to open the file. The with statement allows you to open the file in a language-robust manner. No matter what happens (exception, quit, etc.), Python guarantees that the file will be closed and all resources accounted for. You don't need to close the file, just exit the block (unindent). It's "Pythonic" and a good habit to get into.

Upvotes: 2

Related Questions