Read CSV file using DictReader
Feb 28, 2022 Janaki Mahapatra, Python
import sys
import os
import csv
with open('samplefile.csv', encoding="utf-8-sig") as csvFile:
csvReader = csv.DictReader(csvFile)
# Get All Columns from the file
columns = csvReader.fieldnames;
# Check if there is any columns
# csvReader.fieldnames return None as None ClassType if the file is empty
if(columns != None):
# Lets check if the file has any row, Lets readn the first row only, we dont need to read all
checkRowExists = False
for row in csvReader:
checkRowExists = True
break
if(checkRowExists == True):
print(csvReader)
else:
print("no rows found")
else:
print("File is blank")