Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raise error if not header found(csv files)

Tags:

python

Reading CSV files. I want to raise error message if there is no any header from following list. It must be atleast one header in csv file. Headers are age sex city. I'm trying like this. thanks

with open('data.csv') as f:
  cf = csv.DictReader(f, fieldnames=['city'])
  for row in cf:
    print row['city']
like image 323
Shah Avatar asked Dec 04 '25 06:12

Shah


1 Answers

How about this?

import csv

with open('data.csv', 'rb') as inf:
    cf = csv.reader(inf)

    header = cf.next()
    if header != ['Age', 'Sex', 'City']:
        print "No header found"
    else:
        for row in cf:
            print row[2]
like image 86
Hugh Bothwell Avatar answered Dec 05 '25 21:12

Hugh Bothwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!