← Learning Hub
Intermediate

Working with JSON and CSV Files

Two file types you will meet everywhere: JSON (data from websites and APIs) and CSV (spreadsheet tables). Python reads and writes both with built-in modules.

Most programs need to exchange data with the outside world: download data from a website, export a report for Excel, read settings from a file. JSON and CSV are the two most common formats. JSON handles nested data (an order with a list of items); CSV handles flat tables (one row per sale). Python's built-in json and csv modules handle the details for you.

JSON

Example
You can edit this code.

CSV

csv.DictWriter and csv.DictReader treat each row as a dictionary, using the header row for the keys.

Example
You can edit this code.
Always pass encoding="utf-8" so Hindi text and ₹ signs work on every computer, and newline="" when writing CSV so Windows doesn't add blank lines.
For big tables and number crunching, the pandas library reads CSV and Excel files in one line: pd.read_csv("sales.csv").
Key points
  • json.dumps / json.loads convert to and from text; dump / load use files.
  • csv.DictReader and DictWriter treat rows as dictionaries.
  • Use encoding="utf-8" and newline="" for CSV.

📝 Test yourself

1. Which function turns a Python dict into JSON text?
2. What type are values read by csv.DictReader?
3. Fill in the module name:
import rows = list(csv.DictReader(f))