Skip to content Skip to sidebar Skip to footer

Check For Number Of Columns In Each Row Of Csv

I have the following Python code: import os import csv import sys g = open('Consolidated.csv', 'wb') for root, dirs, files in os.walk('D:\\XXX\\YYY\\S1'): for filename in file

Solution 1:

len(row)

will give the number of columns in the row.

You can do

for row in reader:
    ifnotlen(row)<desired_number_of_columns:
        # process the row here

For example, if your csv file looks like this

1,2,3,4,5a,b,c,d,e
l1,l2
d,e,f,g,h

running

import csv
reader = csv.reader(open("csvfile.csv","r"))
forrowin reader:
    if not len(row)<5:
        print(" ".join(row))

will produce the output

12345ab c d e
d e f g h

ignoring the row with length 2.

Post a Comment for "Check For Number Of Columns In Each Row Of Csv"