File Handling
Learn to read, write, and manage files to save data permanently.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1. Why Learn File Handling?
When your program ends, all variables are lost. Files let you save data permanently so it survives after your program closes.
What Can You Do with Files?
- Save user data — Store settings, preferences, scores
- Read data — Load configuration, import information
- Create logs — Track events and errors
- Process data — Work with CSV, JSON, or text files
2. Opening Files with open()
Use the open() function to work with files. You specify the filename and a mode that tells Python what you want to do.
Mode
Name
What It Does
"r"
Read
Open for reading (file must exist)
"w"
Write
Create new or overwrite existing
"a"
Append
Add to end (keeps existing content)
"x"
Create
Create new (error if file exists)
3. The with Statement (Best Practice)
Always use the with statement when working with files. It automatically closes the file when you are done, even if an error occurs.
4. Reading Files
Method
What It Returns
Best For
.read()
Entire file as one string
Small files
.readline()
One line at a time
Processing line by line
.readlines()
List of all lines
When you need a list
for line in file:
Each line (loop)
Large files (memory efficient)
5. Writing to Files
Use mode "w" to write to a file. This creates a new file or overwrites an existing one.
6. Appending to Files
Use mode "a" to add content to the end of a file without deleting existing content.
Existing Content
Use Case
Deleted (overwritten)
Creating new files, saving fresh data
Kept (added to)
Logs, history, collecting data
7. Checking if a File Exists
Before reading a file, check if it exists to avoid errors:
8. Handling File Errors
Use try-except to handle errors gracefully when working with files:
Error
Cause
FileNotFoundError
File does not exist (reading mode)
PermissionError
No permission to access file
IsADirectoryError
Tried to open a folder as a file
9. Working with CSV Files
CSV (Comma-Separated Values) is a common format for spreadsheet data. Python has a built-in csv module to work with it.
10. Working with JSON Files
JSON (JavaScript Object Notation) is used for configuration files and APIs. Python can easily convert between JSON and dictionaries.
Function
json.dumps(obj)
Convert Python dict → JSON string
json.loads(str)
Convert JSON string → Python dict
json.dump(obj, file)
Write dict to JSON file
json.load(file)
Read JSON file to dict
11. Common Mistakes to Avoid
Mistake
Problem
Solution
Forgetting to close file
Data may not save, file locked
Use with statement
Using "w" instead of "a"
Existing data deleted
Double-check your mode
Forgetting \n
All text on one line
Add \n after each line
Reading non-existent file
Check with os.path.exists()
Wrong encoding
Strange characters appear
Add encoding="utf-8"
12. Practical Examples
Example 1: Simple Note Saver
Example 2: Word Counter
Example 3: Simple Log System
Summary: Quick Reference
Operation
Code
Read entire file
with open("f.txt", "r") as f: text = f.read()
Read lines
Write (overwrite)
with open("f.txt", "w") as f: f.write("text")
with open("f.txt", "a") as f: f.write("more")
Check exists
os.path.exists("f.txt")
Read CSV
csv.reader(file)
Read JSON
Write JSON
json.dump(data, file)
Lesson 9 complete — your programs can now save and load data!
Reading, writing, appending, CSV, JSON — you know how to work with files safely using the with statement. Your programs can now remember things between runs.
🚀 Up next: Exception Handling — learn to catch errors gracefully so your programs never crash unexpectedly.
Practice quiz
Which file mode opens a file for reading (and errors if it doesn't exist)?
- "w"
- "a"
- "r"
- "x"
Answer: "r". Mode "r" opens for reading; the file must already exist.
What does opening a file in mode 'w' do to existing content?
- Appends to the end
- Overwrites (deletes) it
- Raises an error
- Leaves it unchanged
Answer: Overwrites (deletes) it. Mode "w" creates a new file or overwrites an existing one, deleting its content.
Which mode adds to the end of a file without deleting existing content?
- "a"
- "w"
- "r"
- "x"
Answer: "a". Mode "a" (append) keeps existing content and adds to the end.
Why is 'with open(...) as file:' the recommended way to handle files?
- It runs faster
- It automatically closes the file, even if an error occurs
- It allows multiple modes at once
- It compresses the file
Answer: It automatically closes the file, even if an error occurs. The with statement auto-closes the file when the block ends, even on errors.
What does the .read() method return?
- A list of lines
- One line at a time
- The entire file as one string
- The number of characters
Answer: The entire file as one string. .read() returns the whole file content as a single string.
Which method returns a list of all lines in a file?
- .read()
- .readline()
- .readlines()
- .lines()
Answer: .readlines(). .readlines() returns a list where each element is one line.
Does .write() automatically add a newline at the end of each call?
- Yes, always
- No, you must add yourself
- Only in append mode
- Only for the first line
Answer: No, you must add yourself. .write() does not add line breaks; you add yourself for separate lines.
Which exception is raised when reading a file that doesn't exist?
- FileNotFoundError
- PermissionError
- ValueError
- KeyError
Answer: FileNotFoundError. Reading a missing file raises FileNotFoundError.
Which function checks whether a file exists before opening it?
- os.exists()
- os.path.exists()
- file.exists()
- os.check()
Answer: os.path.exists(). os.path.exists('file.txt') returns True if the path exists.
Which json function reads a JSON file directly into a Python object?
- json.loads(str)
- json.dumps(obj)
- json.load(file)
- json.dump(obj, file)
Answer: json.load(file). json.load(file) reads from an open file object into Python; loads is for strings.
Continue this course
- Previous: Dictionaries
- Next: Exception Handling