Read and Write CSV files (2024)

The CSV (Comma Separated Values) format is a common and straightforward way to store tabular data. To represent a CSV file, it should have the .csv file extension.

Now, let's proceed with an example of the info .csv file and its data.

SN, Name, City1, Michael, New Jersey2, Jack, California

Working With CSV Files in Python

Python provides a dedicated csv module to work with csv files. The module includes various methods to perform different operations.

However, we first need to import the module using:

import csv

Read CSV Files with Python

The csv module provides the csv.reader() function to read a CSV file.

Suppose we have a csv file named people.csv with the following entries.

Name, Age, ProfessionJack, 23, DoctorMiller, 22, Engineer

Now, let's read this csv file.

import csvwith open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)

Output

['Name', 'Age', 'Profession']['Jack', '23', 'Doctor']['Miller', '22', 'Engineer']

Here, we have opened the people.csv file in reading mode using:

with open(airtravel.csv', 'r') as file:

We then used the csv.reader() function to read the file. To learn more about reading csv files, Python Reading CSV Files.

Using csv.DictReader() for More Readable Code

The csv.DictReader() class can be used to read the CSV file into a dictionary, offering a more user-friendly and accessible method.

Suppose we want to read the following people.csv file.

Name, Age, ProfessionJack, 23, DoctorMiller, 22, Engineer

Now let's read this file.

import csvwith open('people.csv', 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(row)

Output

{'SN': '1', ' Name': ' Michael', ' City': ' New Jersey'}{'SN': '2', ' Name': ' Jack', ' City': ' California'}

In this example, we have read data from the people.csv file and print each row as a dictionary.

Here, we used csv.DictReader(file), which treats the first row of the CSV file as column headers and each subsequent row as a data record.

Write to CSV Files with Python

The csv module provides the csv.writer() function to write to a CSV file.

Let's look at an example.

import csvwith open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(["SN", "Movie", "Protagonist"]) writer.writerow([1, "Lord of the Rings", "Frodo Baggins"]) writer.writerow([2, "Harry Potter", "Harry Potter"])

When we run the above program, a protagonist.csv file is created with the following content:

SN,Movie,Protagonist1,Lord of the Rings,Frodo Baggins2,Harry Potter,Harry Potter

In this example, we have created the CSV file named protagonist.csv in the writing mode.

We then used the csv.writer() function to write to the file. To learn more about writing to a csv file, Python Writing CSV Files.

Here,

  • writer.writerow(["SN", "Movie", "Protagonist"]) writes the header row with column names to the CSV file.
  • writer.writerow([1, "Lord of the Rings", "Frodo Baggins"]) writes the first data row to the CSV file.
  • writer.writerow([2, "Harry Potter", "Harry Potter"]) writes the second data row to the CSV file.

Writing Dictionaries to CSV Files

We can use the csv.DictWriter() class to write dictionary data into a CSV file, which is useful for more structured data. For example,

import csvwith open('players.csv', 'w', newline='') as file: fieldnames = ['player_name', 'fide_rating'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'player_name': 'Magnus Carlsen', 'fide_rating': 2870}) writer.writerow({'player_name': 'Fabiano Caruana', 'fide_rating': 2822}) writer.writerow({'player_name': 'Ding Liren', 'fide_rating': 2801})

The program creates a players.csv file with the following entries:

player_name,fide_ratingMagnus Carlsen,2870Fabiano Caruana,2822Ding Liren,2801

In this example, we have written data to the players.csv file using csv.DictWriter(file, fieldnames=fieldnames).

The writer.writeheader() function writes these column headers to the first row of the file.

And each call to writerow() adds a new row to the CSV file, where each dictionary represents a record with player_name and fide_rating as keys corresponding to the columns.

Using Python Pandas to Handle CSV Files

Pandas is a popular data science library in Python for data manipulation and analysis.

If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease and efficiency.

Note: Before we can use pandas, we need to install and import it. To learn more, visit Install and Import Pandas.

Read CSV Files

To read the CSV file using pandas, we can use the read_csv() function.

import pandas as pdpd.read_csv("people.csv")

Here, the program reads people.csv from the current directory.

Write to a CSV Files

To write to a CSV file, we need to use the to_csv() function of a DataFrame.

import pandas as pd# creating a data framedf = pd.DataFrame([['Jack', 24], ['Rose', 22]], columns = ['Name', 'Age'])# writing data frame to a CSV filedf.to_csv('person.csv')

Here, we have created a DataFrame using the pd.DataFrame() method. Then, the to_csv() function for this object is called, to write into person.csv.

Also Read

  • Python File Operation
Read and Write CSV files (2024)
Top Articles
Executive summary – World Energy Outlook 2023 – Analysis - IEA
Exclusive Mikayla Campinos Leaked: Unauthorized Footage Surfaces Online
Mybranch Becu
Craigslist Motorcycles Jacksonville Florida
Doublelist Paducah Ky
Www Craigslist Louisville
Here's how eating according to your blood type could help you keep healthy
Western Razor David Angelo Net Worth
Matthew Rotuno Johnson
Savage X Fenty Wiki
Dityship
Ktbs Payroll Login
Oriellys St James Mn
Slag bij Plataeae tussen de Grieken en de Perzen
Hope Swinimer Net Worth
Gfs Rivergate
Dr Manish Patel Mooresville Nc
Bx11
Music Go Round Music Store
Puretalkusa.com/Amac
Japanese Mushrooms: 10 Popular Varieties and Simple Recipes - Japan Travel Guide MATCHA
Greyson Alexander Thorn
Dhs Clio Rd Flint Mi Phone Number
Guide to Cost-Benefit Analysis of Investment Projects Economic appraisal tool for Cohesion Policy 2014-2020
DIY Building Plans for a Picnic Table
Promatch Parts
What Is The Lineup For Nascar Race Today
Home Auctions - Real Estate Auctions
How To Make Infinity On Calculator
Fandango Pocatello
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Yoshidakins
4083519708
Best Workers Compensation Lawyer Hill & Moin
Personalised Handmade 50th, 60th, 70th, 80th Birthday Card, Sister, Mum, Friend | eBay
Culvers Lyons Flavor Of The Day
Kelley Blue Book Recalls
Trizzle Aarp
Cheetah Pitbull For Sale
Ashoke K Maitra. Adviser to CMD's. Received Lifetime Achievement Award in HRD on LinkedIn: #hr #hrd #coaching #mentoring #career #jobs #mba #mbafreshers #sales…
Firestone Batteries Prices
The Realreal Temporary Closure
Gregory (Five Nights at Freddy's)
Linkbuilding uitbesteden
Myrtle Beach Craigs List
Cvs Coit And Alpha
Kaamel Hasaun Wikipedia
Plumfund Reviews
Marine Forecast Sandy Hook To Manasquan Inlet
Electric Toothbrush Feature Crossword
2487872771
Gameplay Clarkston
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated:

Views: 5926

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.