Learn: File Handling¶
Four short tutorials that build up your working knowledge of reading and writing files in Python. Each one is a Jupyter notebook — read it in the browser, and edit and run any code cell directly on the page.
The tutorials build on each other, so working through them in order is the fastest path. Each takes roughly fifteen to twenty minutes.
The sequence¶
- Reading files —
open, thewithstatement, reading text line by line and all at once. - Writing files — write modes, appending, and getting written content to disk reliably.
- Working with paths —
pathlibfor paths that work the same on every operating system. - CSV and JSON files — the two file formats you'll meet most often, and the modules that handle them.
Before you start¶
You'll get more from these if you're already comfortable with Python strings, lists, and dictionaries. The String processing and Data structures guides cover what you need.
You don't need Python installed locally — every tutorial runs in your browser. If you'd rather run them on your own machine, each notebook has a download button in the top-right corner.