Mathew K Analytics

Lesson 29 · Python for Data Science

07 Writing CSV, Excel, and JSON Files in Python

In this lesson, we will learn how to save data to CSV, Excel, and JSON files. You will see how these formats help organize and share data easily. Let us get…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb
 

Welcome to Writing Data Files with Python!#

In this lesson, we will learn how to save data to CSV, Excel, and JSON files.

You will see how these formats help organize and share data easily.

Let us get started!

What are CSV, Excel, and JSON files?#

CSV: Table-like text format, works almost anywhere.

Excel: Spreadsheet format, used by Microsoft Excel and Google Sheets.

JSON: Text format for storing data structures, great for apps and websites.

# Let us make some data we will save later
students = [
    {'name': 'Alex', 'age': 18, 'grade': 'A'},
    {'name': 'Ben', 'age': 17, 'grade': 'B'},
    {'name': 'Clara', 'age': 19, 'grade': 'A'},
]

print(students)
[{'name': 'Alex', 'age': 18, 'grade': 'A'}, {'name': 'Ben', 'age': 17, 'grade': 'B'}, {'name': 'Clara', 'age': 19, 'grade': 'A'}]

Writing CSV files with Python#

CSV is a common way to store simple tables.

You can open CSV files with Excel, Numbers, or Google Sheets.

Let us write one!

import csv  # This module helps us write CSV files

with open('students.csv', mode='w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['name', 'age', 'grade'])
    writer.writeheader()
    writer.writerows(students)

print('CSV file students.csv has been written!')
CSV file students.csv has been written!
# Let us check what the CSV file looks like by reading it back.
with open('students.csv', 'r') as file:
    print(file.read())
    
name,age,grade
Alex,18,A
Ben,17,B
Clara,19,A

Writing Excel Files#

Excel is best for rich spreadsheets, with styles and multiple sheets.

We need to use a special package called openpyxl.

If you do not have it yet, install it with:

!pip install openpyxl

# Let us write the data to an Excel file
from openpyxl import Workbook  # openpyxl works for Excel files

wb = Workbook()
ws = wb.active
ws.append(['name', 'age', 'grade'])  # Add header
for student in students:
    ws.append([student['name'], student['age'], student['grade']])

wb.save('students.xlsx')
print('Excel file students.xlsx has been saved!')
Excel file students.xlsx has been saved!
# Let us check that our Excel file exists.
import os
print('students.xlsx exists:', os.path.exists('students.xlsx'))
students.xlsx exists: True

Writing JSON Data#

JSON files are extremely useful for apps and web development.

They store data as text, similar to Python dictionaries and lists.

Let us write our students' information to a JSON file.

import json  # Built-in for handling JSON

with open('students.json', 'w') as file:
    json.dump(students, file, indent=2)

print('JSON file students.json has been created!')
JSON file students.json has been created!
# Let us read and print our JSON file
with open('students.json') as file:
    data = json.load(file)
    print(data)
    
[{'name': 'Alex', 'age': 18, 'grade': 'A'}, {'name': 'Ben', 'age': 17, 'grade': 'B'}, {'name': 'Clara', 'age': 19, 'grade': 'A'}]

Handling errors: What if saving fails?#

Sometimes, writing files can fail.

Let us safely handle problems using try and except.

# Let us try saving to a protected folder
try:
    with open('/students.csv', 'w') as file:
        file.write('demo')
# Except will run if the above fails
except PermissionError:
    print('Could not write to that location!')
except Exception as e:
    print('Something else went wrong:', e)
    
Could not write to that location!

Updating and removing data in files#

Suppose a student changes class or leaves.

We need to update or remove information. How?

Let us update and re-save our files.

# Update Clara's grade
for student in students:
    if student['name'] == 'Clara':
        student['grade'] = 'B'

print(students)
[{'name': 'Alex', 'age': 18, 'grade': 'A'}, {'name': 'Ben', 'age': 17, 'grade': 'B'}, {'name': 'Clara', 'age': 19, 'grade': 'B'}]
# Remove Ben from the list
students = [s for s in students if s['name'] != 'Ben']
print(students)
[{'name': 'Alex', 'age': 18, 'grade': 'A'}, {'name': 'Clara', 'age': 19, 'grade': 'B'}]
# Now save the updated list to all three formats again
# CSV
with open('students_updated.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['name', 'age', 'grade'])
    writer.writeheader()
    writer.writerows(students)
# Excel
wb = Workbook()
ws = wb.active
ws.append(['name', 'age', 'grade'])
for student in students:
    ws.append([student['name'], student['age'], student['grade']])
wb.save('students_updated.xlsx')
# JSON
with open('students_updated.json', 'w') as file:
    json.dump(students, file, indent=2)
print('All updated files saved.')
All updated files saved.

Filtering and sorting before writing#

Let us write a file with only students who got an A, sorted by age from youngest to oldest.

# Filter for A grades, sort by age
top_students = [s for s in students if s['grade'] == 'A']
top_students = sorted(top_students, key=lambda s: s['age'])

with open('top_students.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['name', 'age', 'grade'])
    writer.writeheader()
    writer.writerows(top_students)

print('Top students saved to top_students.csv')
Top students saved to top_students.csv

Using pandas for more powerful file writing#

pandas is a super popular tool in data science.

It makes reading, writing, and changing big tables very easy.

Let us use pandas to write a CSV and Excel file.

# Install pandas if you do not have it already
!pip install pandas openpyxl
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages)
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages)
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages)
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Local\Programs\Python\Python312\Lib\site-packages)
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages)
WARNING: Ignoring invalid distribution ~illow (C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages)
Requirement already satisfied: pandas in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (2.3.0)
Requirement already satisfied: openpyxl in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (3.1.5)
Requirement already satisfied: numpy>=1.26.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pandas) (2.2.6)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\makmw\appdata\roaming\python\python312\site-packages (from pandas) (2.9.0.post0)
Requirement already satisfied: pytz>=2020.1 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pandas) (2024.2)
Requirement already satisfied: tzdata>=2022.7 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pandas) (2025.1)
Requirement already satisfied: et-xmlfile in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openpyxl) (2.0.0)
Requirement already satisfied: six>=1.5 in c:\users\makmw\appdata\roaming\python\python312\site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)
import pandas as pd

df = pd.DataFrame(students)
df.to_csv('students_pandas.csv', index=False)
df.to_excel('students_pandas.xlsx', index=False)
print('Files created with pandas!')
Files created with pandas!

Mini-project: Keeping Track of Your Daily Mood#

Let us build a tiny mood tracker.

You will enter your mood, and the script will save it in all three formats.

# Get today's mood
from datetime import date
today = str(date.today())
mood = input('How do you feel today? (happy, sad, excited): ')

entry = {'date': today, 'mood': mood}
print(entry)
{'date': '2025-08-13', 'mood': 'happy'}
 
# Save mood as CSV
with open('mood.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['date', 'mood'])
    writer.writeheader()
    writer.writerow(entry)

# Save as Excel
wb = Workbook()
ws = wb.active
ws.append(['date', 'mood'])
ws.append([entry['date'], entry['mood']])
wb.save('mood.xlsx')

# Save as JSON
with open('mood.json', 'w') as file:
    json.dump(entry, file, indent=2)

print('Your mood is saved in mood.csv, mood.xlsx, and mood.json!')
Your mood is saved in mood.csv, mood.xlsx, and mood.json!

Best practices when writing files#

  • Always open files in the correct mode ('w' for write)
  • Use newline='' for CSV files to prevent blank lines
  • Use with statement so files always close safely
  • Add indent to JSON for easy reading

Small habits keep your code bug-free and readable!

Troubleshooting tips#

If a file does not save:

  • Check the path and spelling
  • Make sure the folder exists
  • Try running your code as administrator

If saved data looks wrong:

  • Double-check for typos in your data or code
# Quick check: Try saving an empty list
empty_students = []
with open('empty.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['name', 'age', 'grade'])
    writer.writeheader()
    writer.writerows(empty_students)
print('Empty CSV still works!')
Empty CSV still works!

Extra tips and tricks#

  • Add more columns by just changing your data and headers
  • Try writing a list of dictionaries with more fields to practice
  • Open your files in different programs to compare how they look

Your turn: Save your favorite movies#

  • Make a list of three favorite movies, with title and year
  • Write them to a CSV, Excel, and JSON file
  • Change the code from before to fit your data

Summary and next steps#

You learned to write Python data to CSV, Excel, and JSON files.

You should now be able to:

  • Create small data sets
  • Save them in different formats
  • Update or filter your data

Keep experimenting and happy coding!

If you liked this lesson...#

Please like this video, subscribe, and leave a comment with your favorite file format.

Share this with your friends so they can learn too.

See you in the next Python adventure!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.