- What is file handling — working with files in Python
- Why it's important — storing and retrieving data
- File modes — reading, writing, appending
- The file object — how Python represents files
- Reading files — different ways to read
- Writing files — creating and writing data
- The with statement — safe file handling
What is File Handling?
File handling is the process of working with files in a computer program. It involves creating, opening, reading, writing, and closing files to store and retrieve data permanently.
Think of a file like a notebook. When you write in a notebook, you're storing information. When you read it later, you're retrieving that information. Similarly, file handling allows your Python programs to store data permanently and retrieve it whenever needed.
💡 Key concept: File handling is essential because it allows programs to store data permanently. Without it, all data would be lost when the program ends. Files enable us to save, share, and process data over time.
Why is File Handling Important?
Why We Need File Handling
# Without file handling, all data is temporary
# Variables store data only while the program runs
name = "Alice"
age = 25
# When the program ends, this data is lost forever!
# With file handling, data is permanent
# Save data to a file
with open("user_data.txt", "w") as file:
file.write("Alice,25")
# Later, you can read it back
with open("user_data.txt", "r") as file:
data = file.read()
print(data) # Alice,25
# Real-world applications of file handling:
# 1. Data Storage and Retrieval
# - User profiles
# - Application settings
# - Game progress
# 2. Data Processing
# - Reading CSV files for analysis
# - Processing log files
# - Handling configuration files
# 3. Data Exchange
# - Reading JSON files from APIs
# - Writing reports
# - Exporting data
# 4. Web Development
# - Serving static files
# - Handling file uploads
# - Generating files for download
# 5. Scientific Computing
# - Reading datasets
# - Saving results
# - Processing large files
Why file handling matters:
- Permanent storage — data survives after program ends
- Data exchange — share data between programs
- Configuration — store settings and preferences
- Logging — keep records of program activity
- Data analysis — process large datasets
Quick Check: Why is file handling important? (Answer: It allows permanent storage of data)
File Modes in Python
Understanding File Access Modes
# File modes specify how a file is opened
# 1. 'r' - Read mode (default)
# Opens a file for reading
file = open("myfile.txt", 'r')
# You can only read, cannot write
# File must exist, or it raises an error
# 2. 'w' - Write mode
# Opens a file for writing
file = open("myfile.txt", 'w')
# Creates a new file or overwrites existing one
# You can write, cannot read
# 3. 'a' - Append mode
# Opens a file for appending
file = open("myfile.txt", 'a')
# Adds new content at the end of the file
# File is created if it doesn't exist
# 4. 'x' - Exclusive creation
# Creates a new file, fails if it exists
file = open("newfile.txt", 'x')
# Useful for preventing accidental overwrites
# 5. 'r+' - Read and write mode
# Opens a file for both reading and writing
file = open("myfile.txt", 'r+')
# Can read and write, file must exist
# 6. 'w+' - Write and read mode
# Opens a file for writing and reading
file = open("myfile.txt", 'w+')
# Creates new file or overwrites existing
# 7. 'a+' - Append and read mode
# Opens a file for appending and reading
file = open("myfile.txt", 'a+')
# Can append and read, creates if not exists
# Additional 'b' for binary mode
# 'rb' - Read binary
# 'wb' - Write binary
# 'ab' - Append binary
# Mode summary table:
# Mode | Read | Write | Create | Overwrite | Position
# r | Yes | No | No | No | Beginning
# w | No | Yes | Yes | Yes | Beginning
# a | No | Yes | Yes | No | End
# x | No | Yes | Yes | No | Beginning
# r+ | Yes | Yes | No | No | Beginning
# w+ | Yes | Yes | Yes | Yes | Beginning
# a+ | Yes | Yes | Yes | No | End
File mode summary:
- r — Read only (default)
- w — Write (overwrites)
- a — Append (adds to end)
- x — Exclusive creation
- r+ — Read and write
- w+ — Write and read
- a+ — Append and read
- b — Binary mode (combine with above)
Quick Check: What mode should you use to add content to the end of a file? (Answer: 'a' or append mode)
The File Object
Understanding Python's File Object
# When you open a file, Python returns a file object
# This object has methods for reading, writing, and managing files
# Opening a file creates a file object
file = open("example.txt", "r")
print(type(file)) #
# File object properties
print(f"File name: {file.name}") # example.txt
print(f"File mode: {file.mode}") # r
print(f"File closed: {file.closed}") # False
print(f"File encoding: {file.encoding}") # utf-8
# Common file object methods:
# read() — Read the entire file
# readline() — Read one line
# readlines() — Read all lines into a list
# write() — Write a string to the file
# writelines() — Write a list of strings
# close() — Close the file
# tell() — Get current file position
# seek() — Move to a position in the file
# flush() — Flush the buffer
# Checking if a file object is readable/writable
if file.readable():
print("File is readable")
if file.writable():
print("File is writable")
# Don't forget to close files!
file.close()
print(f"File closed: {file.closed}") # True
# Trying to operate on a closed file raises an error
# file.read() # ValueError: I/O operation on closed file
File object key points:
- File object — returned by open() function
- Methods — read, write, close, seek, tell
- Properties — name, mode, closed, encoding
- Always close — to free system resources
Quick Check: Why should you close files? (Answer: To free system resources and ensure data is saved)
Reading from Files
Different Ways to Read Files
# Reading files in Python
# Create a sample file first
with open("sample.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")
# 1. read() - Read the entire file
with open("sample.txt", "r") as file:
content = file.read()
print("Entire file:")
print(content)
# 2. readline() - Read one line at a time
with open("sample.txt", "r") as file:
print("\nReading line by line:")
line1 = file.readline() # "Line 1\n"
line2 = file.readline() # "Line 2\n"
print(f"Line 1: {line1.strip()}")
print(f"Line 2: {line2.strip()}")
# 3. readlines() - Read all lines into a list
with open("sample.txt", "r") as file:
lines = file.readlines()
print("\nAll lines as list:")
print(lines)
# 4. Iterating over a file (most efficient)
print("\nIterating over file:")
with open("sample.txt", "r") as file:
for line in file:
print(f"Line: {line.strip()}")
# 5. Reading a specific number of characters
with open("sample.txt", "r") as file:
first_5_chars = file.read(5)
print(f"First 5 characters: '{first_5_chars}'")
# 6. Reading from a specific position (seek)
with open("sample.txt", "r") as file:
file.seek(5) # Move to position 5
print(f"From position 5: {file.read()}")
# 7. Checking current position (tell)
with open("sample.txt", "r") as file:
print(f"Position: {file.tell()}") # 0
file.read(3)
print(f"Position: {file.tell()}") # 3
# Reading non-existent file (error handling)
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
Reading methods:
- read() — whole file as a string
- readline() — one line at a time
- readlines() — all lines as a list
- Iteration — most memory-efficient
- seek()/tell() — move around the file
Quick Check: Which method reads the entire file as a string? (Answer: read())
Writing to Files
Creating and Writing Files
# Writing to files in Python
# 1. write() - Write a string
with open("write_example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a second line.\n")
file.write("And a third line.\n")
# 2. writelines() - Write a list of strings
with open("writelines_example.txt", "w") as file:
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)
# 3. Appending to a file
with open("append_example.txt", "a") as file:
file.write("This line is appended.\n")
file.write("So is this one.\n")
# 4. Creating a file with 'x' mode
try:
with open("new_file.txt", "x") as file:
file.write("This file is newly created!\n")
except FileExistsError:
print("File already exists!")
# 5. Writing different data types
with open("data.txt", "w") as file:
# Convert to string before writing
number = 42
name = "Alice"
file.write(f"Number: {number}\n")
file.write(f"Name: {name}\n")
# 6. Writing multiple lines with join
data = ["Apple", "Banana", "Cherry"]
with open("fruits.txt", "w") as file:
file.write("\n".join(data))
# 7. Writing large files efficiently
def write_large_file(filename, num_lines):
with open(filename, "w") as file:
for i in range(num_lines):
file.write(f"Line number: {i}\n")
# write_large_file("large.txt", 10000)
# 8. Checking if writing was successful
with open("test_write.txt", "w") as file:
written = file.write("Hello, Python!")
print(f"Characters written: {written}") # 14
Writing methods:
- write() — write a single string
- writelines() — write a list of strings
- 'w' mode — overwrite existing content
- 'a' mode — append to the end
- 'x' mode — create new file (fails if exists)
Quick Check: What mode should you use to overwrite an existing file? (Answer: 'w' mode)
The with Statement
Safe and Efficient File Handling
# The with statement automatically handles file closing
# Without 'with' (manual closing)
file = open("manual.txt", "w")
file.write("Hello")
file.close() # Must remember to close!
# With 'with' (automatic closing)
with open("auto.txt", "w") as file:
file.write("Hello")
# File is automatically closed here
# Multiple files with 'with'
with open("file1.txt", "w") as f1, open("file2.txt", "w") as f2:
f1.write("Content of file 1")
f2.write("Content of file 2")
# Reading and writing in the same with block
with open("source.txt", "r") as source, open("dest.txt", "w") as dest:
content = source.read()
dest.write(content.upper())
# Using with for binary files
with open("image.jpg", "rb") as file:
data = file.read()
# Process binary data
# Why use 'with':
# 1. Automatic closing — no need to call close()
# 2. Exception safe — file closes even if error occurs
# 3. Cleaner code — less boilerplate
# 4. Resource management — ensures proper cleanup
# Equivalent without 'with' (more code):
try:
file = open("example.txt", "w")
file.write("Hello")
except Exception as e:
print(f"Error: {e}")
finally:
file.close()
# with does all this automatically!
Why use 'with':
- Automatic closing — no need to call close()
- Exception safe — closes even on errors
- Cleaner code — less boilerplate
- Resource management — ensures proper cleanup
Quick Check: What is the main advantage of using 'with' for file handling? (Answer: Automatic file closing)
Error Handling with Files
Handling File-Related Errors
# Common file handling errors and how to handle them
# 1. FileNotFoundError
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file doesn't exist!")
# 2. PermissionError
try:
with open("/protected/file.txt", "w") as file:
file.write("Hello")
except PermissionError:
print("You don't have permission to write to this file!")
# 3. IsADirectoryError
try:
with open("/home/user", "r") as file:
content = file.read()
except IsADirectoryError:
print("Cannot open a directory as a file!")
# 4. UnicodeDecodeError (reading binary as text)
try:
with open("image.jpg", "r") as file:
content = file.read()
except UnicodeDecodeError:
print("File contains binary data! Use 'rb' mode.")
# 5. General Exception handling
try:
with open("somefile.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"Unexpected error: {e}")
# 6. Using os.path to check before opening
import os
filename = "data.txt"
if os.path.exists(filename):
with open(filename, "r") as file:
content = file.read()
else:
print(f"'{filename}' does not exist.")
# 7. os.path checks
if os.path.isfile("myfile.txt"):
print("It's a regular file")
if os.path.isdir("myfolder"):
print("It's a directory")
if os.access("myfile.txt", os.R_OK):
print("File is readable")
if os.access("myfile.txt", os.W_OK):
print("File is writable")
Common file errors:
- FileNotFoundError — file doesn't exist
- PermissionError — don't have permission
- IsADirectoryError — trying to open a directory
- UnicodeDecodeError — wrong encoding
- Always handle errors — robust programs handle exceptions
Quick Check: What exception is raised when a file doesn't exist? (Answer: FileNotFoundError)
Try It Yourself
Experiment with file handling in the editor below. Try reading, writing, and managing files.
FILE HANDLING INTRODUCTION PRACTICE
========================================
1. WRITING TO A FILE
File 'my_file.txt' created and written!
2. READING FROM A FILE
File content:
Hello, World!
This is line 2
This is line 3
3. READING LINE BY LINE
Line: Hello, World!
Line: This is line 2
Line: This is line 3
4. APPENDING TO A FILE
Appended new line!
5. READING UPDATED FILE
Hello, World!
This is line 2
This is line 3
This line was appended
6. USING READLINES()
Number of lines: 4
Line 1: Hello, World!
Line 2: This is line 2
Line 3: This is line 3
Line 4: This line was appended
File handling introduction practice complete!
You've Got It!
You now understand the fundamentals of file handling in Python. You know how to open, read, write, and manage files safely and efficiently.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is file handling in Python?
Why should I use 'with' when working with files?
What is the difference between 'r', 'w', and 'a' modes?
What's a common interview question about file handling?
How do I handle file-related errors?
What happens if I forget to close a file?
Where to Go From Here
Now that you understand file handling basics, check out these related topics:
Create File
Learn different ways to create files in Python.
Learn More →Read Files
Master reading files with different methods.
Learn More →Write to File
Learn how to write data to files effectively.
Learn More →