STR Coding Club logo STR Coding ClubLearn to code, together
Python and Practice

Python File Handling Practice That Makes Programs Remember

Every term, about week five, someone in our club builds a quiz or a to-do list that works perfectly, closes the program, opens it again and finds everything gone.

A laptop showing a short Python script next to an open text file with a list of foods

Every term, about week five, someone in our club builds a quiz or a to-do list that works perfectly, closes the program, opens it again and finds everything gone. That moment is the best possible introduction to Python file handling practice. The program was fine. It just had nowhere to remember things.

Files are where beginner programs start feeling like real tools, and they are also where a surprising number of confusing errors live. Below is the sequence I use with new coders: six small exercises that build on each other, the mistakes each one tends to expose, and why I teach them in this order rather than the order most textbooks use.

Why Python File Handling Practice Comes Before Libraries

Plenty of courses jump from lists and dictionaries straight to libraries such as pandas or json. I think that skips a step. Reading and writing a plain text file teaches three ideas that come back everywhere later: that data on disk is just text until you give it meaning, that a program can fail because of the outside world rather than its own logic, and that you need to clean up after yourself.

A learner who has written ten lines that read a file, split each line and convert numbers will understand a CSV reader in minutes. A learner who started with the library often has no idea what it is doing for them, and freezes when it throws an error.

The Setup You Need

Keep it minimal. One folder, one Python file, and one text file in the same folder. Most early file errors are actually location errors, so I ask everyone to print the current working directory first using os.getcwd() and check it matches the folder they think they are in. It takes ten seconds and prevents half the "FileNotFoundError" questions I would otherwise answer.

Name the text file something boring like notes.txt. Spaces and capital letters in filenames cause trouble on some systems, and beginners do not need extra problems.

Six Exercises in Order

Each exercise should take between 10 and 25 minutes. Do them in one sitting or across a week, but do not skip ahead.

1. Read and print

Open notes.txt with a with statement and print every line. Then print the number of lines. Most learners notice blank lines between their output, which is the perfect moment to explain the hidden newline character and strip().

2. Write a new file

Ask the user for three favourite foods and write them to foods.txt, one per line. Open the file in a text editor afterwards to check. Forgetting to add the newline yourself is the classic slip here.

3. Append instead of overwrite

Run exercise two again. The old foods are gone. Now change the mode from "w" to "a" and run it twice. Seeing data disappear once teaches the difference between modes better than any table.

4. Count words

Read a paragraph from a file and count how many times each word appears, storing the counts in a dictionary. If dictionaries still feel shaky, the dictionary practice exercises on this site make a good warm-up.

5. Numbers from text

Store ten test scores in a file, one per line, then read them and print the average. The first run usually crashes because the values are strings. Converting with int() and handling an empty last line is the real lesson.

6. Save and load a small app

Take any program the learner already built, such as a to-do list, and make it save on exit and load on start. This is the payoff exercise, and it is the one people show their friends.

The Mistakes Each Exercise Reveals

I keep a short list on the whiteboard during these sessions, because the same errors appear every term.

Error or symptomUsual causeQuick fix
FileNotFoundErrorScript runs from a different folderPrint os.getcwd() and move the file or use a full path
Blank lines between outputNewline kept at the end of each lineCall strip() on each line
Data vanishedOpened with "w" instead of "a"Use append mode when adding
ValueError on int()Empty line or stray spaceSkip empty lines, strip first
Changes not savedFile never closedUse a with block every time

When a learner hits one of these, I ask them to read the last line of the traceback aloud before I say anything. Our guide on reading a Python error message walks through that habit in more detail.

Where Common Advice Goes Wrong

A popular tip is to always wrap file code in try and except from day one. I disagree for complete beginners. A bare except that prints "something went wrong" hides the exact error message they need to learn from. In the first few weeks, I would rather they see a full FileNotFoundError and understand it.

Once the six exercises feel easy, then introduce try and except, and catch the specific error only. Catching FileNotFoundError and creating an empty file on first run is a sensible pattern. Catching everything is not.

The other advice I push back on is "always use the csv module". For a list of names, plain lines are simpler and easier to debug. Reach for csv when values contain commas or you have several columns.

Taking It Further

When the basics are solid, there are three natural next steps. First, the json module, which turns a dictionary into text and back with two function calls, ideal for saving app settings. Second, pathlib, which makes paths readable and works the same on Windows and macOS. Third, reading large files line by line rather than all at once, which matters the first time someone tries to open a 200 MB log file.

In our club, a good group challenge is a shared high score file: each person's game writes to the same text file, and one person writes a script that reads it and prints a ranked table.

FAQ

Should beginners use open() and close() or with?

Use with from the start. It closes the file automatically, even if the program crashes halfway, and it is what nearly all modern Python code looks like.

Why does my file say it does not exist when I can see it?

Your script is almost certainly running from a different folder than the file. Print the working directory, then either move the file there or give the full path.

Is reading files useful outside small projects?

Very. Log analysis, data cleaning, configuration and simple databases all start with the same open, read, split and convert pattern you practise here.

The Practical Takeaway

Work through the six exercises in order, keep the error table nearby and resist adding try and except until you can explain each error yourself. Then add saving to a program you already wrote, so it finally remembers. More short drills live in our Python practice section.

IA
Imogen Achebe

Imogen started a coding club at her school and now trains volunteer mentors. She writes about first steps in coding and projects that work for groups of mixed ability.

More posts by Imogen

More in Python and Practice

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto