PurpleCoffee
PurpleCoffee

Reputation: 35

Check if specific column in csv file contains data

I need to check if the third column of my row in a CSV file contains 2016.

My code so far:

    import csv
    import pandas
    from docutils.utils import column_indices
    from bsddb.dbtables import contains_metastrings
    file = open("Advertising.csv")

    #write new file
    c = csv.writer(open("boop.csv", "wb"))
    #read in original file
    readCSV = csv.reader(file,delimiter= ",")


    for row in readCSV :
        print "something"
        #if contains(2016)
        if readCSV.index_col(2).Contains('2016') :
            print "2016 spotted"
            c.writerow(row)
    
    file.close()

The line checking the third column is wrong and produces and error:

AttributeError: '_csv.reader' object has no attribute 'index_col'

Can anyone help with this?

Upvotes: 0

Views: 21974

Answers (1)

Loïc G.
Loïc G.

Reputation: 3157

You don't need pandas for this. csv module would be fine

import csv

with open("file.csv", "rb") as f:
    csvreader = csv.reader(f, delimiter=",")
    for row in csvreader:
        if "2016" in row[2]:
            print "2016 spotted"

Upvotes: 5

Related Questions