Home » Python15 February 2016

Python: Read Write CSV

In this article, I will be showing how to read data from a CSV file and write data to a new CSV file using Python programming language.

Here’s a scenario: Suppose, I have a CSV file with 3 columns (user_id, item_id, and star_rating). It has data of 100 users. Each user has rated 20 different items. So, altogether there are 100 * 20 = 2000 entries in the CSV file.

Download: Input CSV File (CSV file which we will be working on)

Here’s how the CSV file looks like:


Now, I have a requirement to select single entry for each user, i.e. I have to select a total of 100 entries having 100 different users.

For this, I will first read the CSV file and create a Python dictionary having single entry for each user. Then, I will use that dictionary to write values to a new CSV file.

Here’s the full source code:

I am reading data from CSV file named dataset-recsys.csv and writing to a new CSV file named dataset-recsys-new.csv.

Download: Output CSV File (CSV file that is the output from above code)

Hope this helps.


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed

Comments are closed.