If you’re learning Python and want to gain real-world, job-ready skills, one of the best places to start is working with data files. Two of the most common formats you’ll encounter are CSV (Comma-Separated Values) and JSON (JavaScript Object Notation). These formats are everywhere—in spreadsheets, APIs, web applications, and data pipelines. This beginner-friendly guide will walk you through what CSV and JSON files are, and how to read, write, and convert them using Python.
Handling JSON and CSV Files in Python for Beginners
What Are CSV and JSON Files?
CSV (Comma-Separated Values)
CSV files are plain text files that look like spreadsheets. Each line represents a row, and values are separated by commas.
Example CSV:
Name, Age, City
Alice,30 ,New York
Bob,25 ,London
Used in:
✔ Excel files
✔ Data reports
✔ Exported database tables
JSON (JavaScript Object Notation)
JSON is a structured format used to store data as key-value pairs, much like a Python dictionary.
Example JSON:
{
“Name”: “Alice”,
“Age”: 30,
“City”: “New York”
}
Used in:
✔ APIs
✔ Web apps
✔ Configuration files
Why Should You Learn This?
- CSV is everywhere in business tools, especially Excel and Google Sheets.
- JSON is the language of the web and APIs.
- Knowing how to handle both formats is crucial for data analysis, automation, and web development.
Step 1: Import the Required Libraries
Python makes things easy with built-in libraries:
import csv
import json
No need to install anything—these come with Python by default.
Working with CSV Files
Reading a CSV File
Assume you have a file people.csv:
Name,Age,City
Alice,30,New York
Bob,25,London
Code to Read:
with open(‘people.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
[‘Name’, ‘Age’, ‘City’]
[‘Alice’, ’30’, ‘New York’]
[‘Bob’, ’25’, ‘London’]
Skipping the Header Row
next(reader) # Skips the first row
Writing to a CSV File
data = [
[‘Name’, ‘Age’, ‘City’],
[‘Charlie’, ’22’, ‘Paris’],
[‘Diana’, ’28’, ‘Berlin’]
]
with open(‘output.csv’, ‘w’, newline=”) as file:
writer = csv.writer(file)
writer.writerows(data)
Reading CSV with Dictionary Format
with open(‘people.csv’, ‘r’) as file:
reader = csv.DictReader(file)
for row in reader:
print(row[‘Name’], row[‘Age’])
Working with JSON Files
Reading JSON
Assume you have a file data.json:
{
“Name”: “Alice”,
“Age”: 30,
“City”: “New York”
}
Python Code:
with open(‘data.json’, ‘r’) as file:
data = json.load(file)
print(data[‘Name’])
Writing JSON
person = {
“Name”: “Bob”,
“Age”: 25,
“City”: “London”
}
with open(‘person.json’, ‘w’) as file:
json.dump(person, file, indent=4)
The indent=4 makes the file more readable.
Converting Between Formats
CSV ➡ JSON
import csv, json
csv_file = ‘people.csv’
json_file = ‘people.json’
data = []
with open(csv_file, ‘r’) as file:
reader = csv.DictReader(file)
for row in reader:
data.append(row)
with open(json_file, ‘w’) as file:
json.dump(data, file, indent=4)
JSON ➡ CSV
with open(‘people.json’, ‘r’) as file:
data = json.load(file)
with open(‘people.csv’, ‘w’, newline=”) as file:
writer = csv.DictWriter(file, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
Common Mistakes to Avoid
Missing newline =” when writing CSV files (causes extra blank lines on Windows)
Always use newline=”
Forgetting to use with open()
Using with automatically closes the file safely
Using single quotes in JSON
JSON only supports double quotes for strings
Real-Life Use Cases
Automate data entry from spreadsheets
Save API responses as JSON
Analyze sales or financial reports
Convert data between systems or formats
Practical Examples
Save API Data as JSON
import requests, json
response = requests.get(‘https://api.agify.io/?name=michael’)
data = response.json()
with open(‘api_data.json’, ‘w’) as file:
json.dump(data, file, indent=4)
Analyze Sales from CSV
import csv
total_sales = 0
with open(‘sales.csv’, ‘r’) as file:
reader = csv.DictReader(file)
for row in reader:
total_sales += float(row[‘Amount’])
print(f”Total Sales: ${total_sales}”)
Summary: Key Takeaways
Feature | CSV | JSON |
Structure | Tabular (rows & columns) | Nested (key-value pairs) |
Use Case | Spreadsheets, reports | APIs, configs, web apps |
Read Tool | csv.reader, DictReader | json.load() |
Write Tool | csv.writer, DictWriter | json.dump() |
- Start small. Test with basic files first.
- Use the right library for the right format.
- Practice converting between formats—it’s a common real-world task.
Conclusion
Handling JSON and CSV files is a core skill in Python, and a beginner-friendly one. With just a few built-in libraries, you can read, write, and convert data easily, whether you’re working with spreadsheets or APIs.
If you’re just starting out and want hands-on practice, Console Flare offers beginner-friendly Python courses with real-world projects like these. You’ll go from reading your first CSV file to automating data tasks confidently.
Learning Python means learning to work with data, and now you’re one step closer.
For more such content and regular updates, follow us on Facebook, Instagram, LinkedIn