readCSV
Define the function readCSV(filename)to so it reads the contents of the CSV file named filename and returns a list of dictionaries corresponding to its contents. The CSV file will have a header file with field names. Each dictionary in the returned list of dictionaries must consist of key-value pairs where the key is a field name. The field name must be paired with the corresponding data value from the record.
For example, if sample.csv contains:
a,b,c
1,2,3
4,5,6
7,8,9
then readCSV('sample.csv')must return this list:
[ { 'a':'1', 'b':'2', 'c':'3' },
{ 'a':'4', 'b':'5', 'c':'6' },
{ 'a':'7', 'b':'8', 'c':'9' }
]
Here is Solution for Above Problem ::
import csv
def readCSV(filename):
x =[]
with open(filename, 'r') as data:
for line in csv.DictReader(data):
x.append(line)
print("Here is Data :: ",x)
filename=input("Enter CSV file name = ")
print(filename)
readCSV(filename)
where this csv file contains data
a,b,c
1,2,3
4,5,6
7,8,9
Input :
sample.csv
Output :
Enter CSV file name = sample.csv Here is Data :: [{'b': '2', 'c': '3', 'a': '1'}, {'b': '5', 'c': '6', 'a': '4'}, {'b': '8', 'c': '9', 'a': '7'}]
Get Answers For Free
Most questions answered within 1 hours.