Reading and Writing Files

A file is data that outlives your program. Python has file handling built in. JavaScript in a browser cannot touch your hard drive for security reasons, it works with files through Node.js on a server or through deliberate user upload in the browser.

This is a genuine language-specific difference driven by where each language usually runs.

Writing a file

PYTHON

import json

records = [{"name": "Ama", "hours": 95}]

with open("members.json", "w") as f:
    json.dump(records, f)

JAVASCRIPT

// Node.js, not the browser
const fs = require("fs");

const records = [{ name: "Ama", hours: 95 }];

fs.writeFileSync("members.json", JSON.stringify(records));
Compare → Python's `with open(...)` opens the file and guarantees it is closed afterwards, even if an error occurs. That guarantee is why `with` is the standard way to handle files in Python. Node.js reads and writes through its fs module.

The three file modes you need: "r" read, "w" write (which erases the file first), and "a" append (which adds to the end). Confusing "w" with "a" has destroyed a lot of data over the years.

✦ The sandbox limitation, stated honestly

The Sankofa sandbox runs Python inside your browser, so it has no access to your real files. The file examples below are written to be correct and runnable on your own machine with Python installed. Everything else in this course runs right here.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Add a third member, save, load, and confirm the count changes. This is the save/load cycle every app performs.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Challenge

Write a function that takes a JSON string containing an array of member records (each with a name and hours) and returns the name of the member with the most hours. If the JSON contains an empty array, return the string "none".

Name it exactly: def top_from_json(text):

3 visible + 2 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back