Working with Files
Learn how to store data permanently by reading and writing text files
Learning Objectives
- Open, read, and close text files
- Write and append data to files
- Use the 'with' statement for safe file handling
- Understand different file modes (r, w, a)
Persistent Data
Until now, all our data disappeared as soon as the program stopped. To save data for later, we need to use Files.
Opening and Closing Files
Python has a built-in open() function. You must always close() a file when you are done to free up resources.
manual_file.py
|
|
The with Statement (Recommended)
Closing files manually is risky—if an error happens, the file might stay open. The with statement handles this automatically.
with_example.py
|
|
File Modes
| Mode | Description |
|---|---|
r |
Read (Default). Error if file doesn’t exist. |
w |
Write. Overwrites the file if it exists. Creates it if not. |
a |
Append. Adds to the end of the file. Creates it if not. |
x |
Create. Fails if the file already exists. |
Writing to a File
writing.py
|
|
Interactive Practice
Try writing a program that asks for a user’s name and saves it to a file called users.txt.
flowchart LR
Input[Get User Name] --> Open[Open users.txt in 'a' mode]
Open --> Write[write name + \n]
Write --> Close[Close File automatically]
Quiz
Complete this quiz with a minimum score of 80% to mark Day 13 as complete.
Loading quiz...
Discussion
Have questions or want to discuss this lesson? Join the conversation below!