Reading CSV with Python
An answer to this question on Stack Overflow.
Question
Im stuck on a problem. Im trying to figure out how to write a program using PYTHON to check whether all the records are the same. so far I came up with the code below. How do I check all records and not just the data within the rows are equal?
import csv
index = 0
def all_same(items):
return all(x == items[0] for x in items)
with open(r'C:\Users\Aaron\Desktop\testfolder\data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ',')
for row in readCSV:
print (row)
print (all_same(row))
the output looks like this:
['1', '1', '1', '2']
False
['1', '1', '1', '1']
True
['1', '1', '1', '1']
True
Answer
You could try this:
import csv
with open(r'C:\Users\Aaron\Desktop\testfolder\data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ',')
firstrow = readCSV.next()
print(all(row==firstrow for row in readCSV))