How to Read CSV File in Python?

How To Read CSV File in Python

In this problem, we are going to see how to read csv file in Python.

Python is a high-level programming language designed to be easy to read and simple to implement.

Reading is the process of receiving or taking in the sense or meaning of letters, symbols, etc., especially by sight or touch. That is general definition of reading.

Reading a file in computer means loading the file in memory. In our case, we are going to do it using python programming language.

A CSV (comma-separated values) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record.

Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

How To Read CSV File in Python

For this python program we are going to use the sample csv file from fsu.edu . You can download the file from here -- Sample CSV File.

There are 6 records in this sample csv. Each record has 5 data fields, First Name, Last name, address, 4th attribute is I think its landmark (but doesn't matter), 5th data attribute is zipcode.

These attribute names are not states as header in the csv file but the values in respective columns represent them.

import csv
  
def read_csv(filename):
    try:
        f = open(filename, "r")
        records = list(csv.reader(f))
        return records
    except Exception as e:
        print(e)
        return False

filename = "sample csv file.csv" records = read_csv(filename) for record in records: print(record) print(f"{len(records)} records read from csv file : {filename}")

Output

['John', 'Doe', '120 jefferson st.', 'Riverside', ' NJ', ' 08075']
['Jack', 'McGinnis', '220 hobo Av.', 'Phila', ' PA', '09119']
['John "Da Man"', 'Repici', '120 Jefferson St.', 'Riverside', ' NJ', '08075']
['Stephen', 'Tyler', '7452 Terrace "At the Plaza" road', 'SomeTown', 'SD', ' 91234']
['', 'Blankman', '', 'SomeTown', ' SD', ' 00298']
['Joan "the bone", Anne', 'Jet', '9th, at Terrace plc', 'Desert City', 'CO', '00123']

6 records read from csv file : sample csv file.csv

Output Image

How To Read Csv In Python

Comments