Python File Handling with PRIMM
Year 10 Computing UK National Curriculum 30-minute lesson
What is File Handling?
Reading data from files stored on computer Writing new data to files Essential skill for real-world programming Allows programs to store and retrieve information
Types of Files in Python
{"left":"Text files (.txt)\nCSV files (.csv)\nJSON files (.json)\nPython files (.py)","right":"Binary files (images, videos)\nConfiguration files\nLog files\nData files"}
PRIMM: Predict
Look at this code: file = open('data.txt', 'r') content = file.read() print(content) file.close() What do you think this code will do?
Opening Files in Python
Use open() function to access files Specify filename and mode Mode 'r' = read, 'w' = write, 'a' = append Always close files when finished Good practice: use 'with' statement
PRIMM: Run & Investigate
Create a file called 'test.txt' with some text Run the code from the Predict activity Try changing the filename What happens if the file doesn't exist? Investigate different file modes
File Handling Workflow
Reading Files - Best Practice
Use 'with' statement for automatic file closing with open('file.txt', 'r') as f: content = f.read() File automatically closes when done Prevents memory leaks and errors
PRIMM: Modify & Make
Modify the code to write to a file instead of read Create a program that asks for user input Write the input to a new file Read the file back and display contents Challenge: Create a simple diary program
Key Takeaways
'File handling is the bridge between your program and the real world of data storage' - Always use 'with' statements - Remember to specify the correct file mode - Handle errors gracefully - Practice makes perfect!