Recent Tutorials and Articles
    How to read CSV files in Python
    Published on: 2018-09-15 15:09:03
    Posted By: Sumit Sain

    This tutorial demonstrates Python way of reading CSV files into either dictionary or list data structures.


    In this tutorial we will read a CSV file to get the data in the form of List and Dictionary data structures.



    We will now see how to read following CSV file into List and List of Dictionary -


    I have got this file saved on path D:\Python_reading.csv in my machine.


    Reading CSV file into List

    import csv
    #Reading CSV file as a List
    with open('D:\Python_reading.csv', 'rb') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader) #to remove csv header
        for row in csvreader:
            print row


    ['1', 'Python', '24']
    ['2', 'Java', '43']
    ['3', 'PHP', '23']
    ['4', '.net', '29']


    Reading CSV file into Dictionary

    import csv
    #Reading CSV file as a Dictionary     
    with open('D:\Python_reading.csv', 'rb') as csvfile:
        dictreader = csv.DictReader(csvfile)
        for r in dictreader:
            print r


    {'Id': '1', 'Value': '24', 'Title': 'Python'}
    {'Id': '2', 'Value': '43', 'Title': 'Java'}
    {'Id': '3', 'Value': '23', 'Title': 'PHP'}
    {'Id': '4', 'Value': '29', 'Title': '.net'}


    Reading CSV file into List of Dictionary

    import csv
    #Reading CSV file as a list of dictionary   
    with open('D:\Python_reading.csv', 'rb') as csvfile:
        listdictreader = csv.DictReader(csvfile)
        data = [val for val in listdictreader]
        print data


    [{'Id': '1', 'Value': '24', 'Title': 'Python'}, {'Id': '2', 'Value': '43', 'Title': 'Java'}, {'Id': '3', 'Value': '23', 'Title': 'PHP'}, {'Id': '4', 'Value': '29', 'Title': '.net'}]



    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Posted By: Sumit Sain
    Published on: 2018-09-15 15:09:03

    Comment Form is loading comments...