import os
import datetime
with open("today.txt", "w+") as file:
file.write(datetime.datetime.now().strftime("%Y-%m-%d"))
with open("today.txt") as file:
print("today.txt contains:", file.read())Python reads and writes files with the built-in open() function. It
returns a file object that you write strings to or read them from, and a
with block closes the file when the block ends. The standard library
adds csv and json for common formats, and os and pathlib for
listing, checking and deleting files. People use files to save results,
keep settings and record what a program did. On this page it runs in
your browser, so you can try it without installing anything.
Run the example first, then paste any snippet below into a new cell to try it.
datetime.datetime.now() gets the current date and time, and
strftime("%Y-%m-%d") turns it into text such as 2026-09-28.
open("today.txt", "w+") creates the file, or empties it if it already
exists, and file.write() writes the date into it. The + in the mode
also allows reading, although the example only writes. When the with
block ends, the file is closed. The last two lines open the file again
in the default read mode and print what it contains. A relative name
like today.txt lands in the working directory, /home/pyodide.
Looping over a file gives one line at a time, with the line break still
at its end. strip() removes it, and splitlines() splits the whole
text into a list without the line breaks:
with open("notes.txt", "w") as file:
file.write("first line\n")
file.write("second line\n")
file.write("third line\n")
with open("notes.txt") as file:
for number, line in enumerate(file, start=1):
print(number, line.strip())
with open("notes.txt") as file:
print(file.read().splitlines())
Mode "a" appends instead of replacing. print() writes to a file when
you pass file=, and it adds the line break for you:
for step in ["loaded data", "cleaned data", "saved results"]:
with open("log.txt", "a") as log:
print("done:", step, file=log)
with open("log.txt") as log:
print(log.read())
Run the cell twice and log.txt has six lines.
The csv module writes rows of values, and json saves dictionaries and
lists in a form you can load back unchanged:
import csv
import json
rows = [["name", "score"], ["Ada", 92], ["Grace", 88]]
with open("scores.csv", "w", newline="") as file:
csv.writer(file).writerows(rows)
with open("scores.csv", newline="") as file:
for row in csv.DictReader(file):
print(row["name"], int(row["score"]))
settings = {"theme": "dark", "font_size": 14, "recent": ["scores.csv"]}
with open("settings.json", "w") as file:
json.dump(settings, file, indent=2)
with open("settings.json") as file:
print(json.load(file))
csv reads every value back as a string, so convert numbers with int()
or float(). For bigger tables, pandas reads a CSV
file into a DataFrame with pd.read_csv().
os and pathlib work with the files themselves rather than their
contents:
import os
from pathlib import Path
print(os.getcwd())
print(sorted(os.listdir()))
print(Path("today.txt").exists(), Path("today.txt").stat().st_size, "bytes")
os.makedirs("reports", exist_ok=True)
Path("reports/summary.txt").write_text("All done\n")
print(sorted(str(p) for p in Path(".").rglob("*.txt")))
os.remove("reports/summary.txt")
print(os.path.exists("reports/summary.txt"))
Files your code saves, like today.txt, appear in the sidebar's Data
tab. Running code and inspecting the result is free. Downloading the
files requires a Premium plan.
open("data.csv")."w" empties a file as soon as it opens, even if you never write
to it. Use "a" to add to the end, or "x" to raise FileExistsError
instead of overwriting.