Writing CSVs With Pandas – Real Python (original) (raw)

In this lesson, you’ll cover how to use pandas to write data to CSV files. Here is a code sample that demonstrates how to add a new employee to a CSV file from the previous lesson:

Take the Quiz: Test your knowledge with our interactive “Reading and Writing CSV Files in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:


Python CSV Parsing

00:00 Once you have the data from a CSV in pandas, you can do all sorts of operations to it as needed. When you want to get that data out of pandas, it can be helpful to put it back into a CSV.

00:11 Let’s quickly add a row for a new employee named Cookie Cat.

00:19 This is more for just showing that we can change the DataFrame—we’re not going to get into how to work with DataFrames too much in this video. Let’s see, I found her on the 4th of July,

00:33 she gets about 20,000 treats a year, and she doesn’t have any sick days left because she’s pretty lazy. All right, let’s print this DataFrame out after we add the row.

00:47 And let’s just see—python pandas_csv.py. All right. So if you notice, we have the new row here. We don’t have the date in the same format—now this is just a date, it’s not a date and a time—but we won’t worry about that too much.

01:01 Everything else looks okay. So what you can actually do is just replace this print statement with a .to_csv(), and just pass in a new filename. So we’ll just say 'hrdata_modified.csv'. Go ahead and run that.

01:19 And we have a new file here, so I’ll open this up—and there you go! Look, you’ve added a new row. You can see that these hired dates are different than they were when we first read them in.

01:33 So, pandas is only saving the string representation of what it has for its own Timestamp object, so depending on where the CSV needs to go after this, you may need to take that into account.

01:46 But that’s enough for now. In these videos, you learned how to read and write CSVs with Python using two separate libraries, and even covered ways to handle nonstandard data.

01:57 If you find yourself working with structured data often, I highly recommend looking into pandas, because it’s a great library. Now it’s time to start using CSVs in your own applications.

02:07 Thanks for watching, and have fun!