Skip to content

How to read a CSV file from Python?

One of the most common tasks in any programming is to read files like csv to process the data. It is pretty easy to read a CSV file from Python as it has in built library for processing csv files.

In the below code csv library is imported on the top then used “with” operator to open the csv file in read mode indicated by “r”, and declare the csv as f. It is important to note that the file will be open only within the “with” code block.

Using the csv dictionary reader function reads the csv file contents and put it in-memory variable called contents then convert the contents into list and assign it to lstContents.

Finally loop through the contents and find the line containing surname “Sergio” and print it. To learn more about loops you can check out How to use if statement and loops in Python.

import csv

with open("Students.csv", "r") as f:
    contents = csv.DictReader(f)
    lstContents= list(contents)

for content in lstContents:
    if content["surname"] == "Sergio":
        print(content)
        break

#Output
{'birthplace': 'Australia',
 'born': '1995-03-14',
 'Major': 'physics',
 'name': 'Andrew',
 'surname': 'Sergio',
 'passed year': '2009'}
Leave a Reply

Your email address will not be published. Required fields are marked *