What exactly is a CSV file?
CSV stands for “Comma Separated Values”. It is the most basic method of storing tabular data in plain text form. We depend on CSV data in our day-to-day lives as data analyst/ scientists, knowing what and how to work with it is essential.The name of a CSV file gives away its structure. Normally, a comma is used to separate each data value in a CSV file. That’s how that structure looks:
employee id, name, department
101, Tom, Finance
102, Jack, HR
....{codeBox}
To be clear, you don’t have to write your own CSV parser. You can utilize a number of libraries that are absolutely suitable. Most scenarios will be covered by the Python csv library. If your task necessitates a large amount of data or numerical analysis, the pandas library also provides CSV parsing capabilities that should take care of the rest.
So let’s get started!
Reading CSV Files With csv
Reading a CSV file with Python’s built-in csv module.Import the csv library
import csv{codeBox}
Open the CSV file
The .open() method is used to open files and return a file object.file = open('employee_data.csv'){codeBox}
Use the csv.reader object to read the CSV file
csvreader = csv.reader(file){codeBox}
How to read the header/column names?
- Create an empty list called headers.
- Use the next() method to fetch the headers.
headers = []headers = next(csvreader)print(headers){codeBox}
Output:
['employee id', 'name', 'department']{codeBox}
How to read the rows/records?
Create an empty list called rows and iterate through the csvreader object and append each row to the rows list.
rows = []for row in csvreader:rows.append(row)print(rows){codeBox}
Output:
[['101', 'Tom', 'Finance'],
['102', 'Jack', 'HR']]{codeBox}
Close the csv file
close() method is used to close the opened file. Once it is closed, we cannot read more from it.file.close(){codeBox}
Here’s what the completed script will look like.
import csvfile = open("employee_data.csv")csvreader = csv.reader(file)headers = []headers = next(csvreader)print(header)rows = []for row in csvreader:rows.append(row)print(rows)file.close(){codeBox}
0 Comments