Python File Handling
Learn how Python programs read, create, write, append, and manage files so your applications can work with persistent data beyond the lifetime of a program.
Learning Objectives
Until now, most of the data used by your Python programs existed only while the program was running. File handling allows your programs to store and retrieve information from files.
- Understand what file handling means.
- Open files using Python.
- Understand common file modes.
- Read complete files and individual lines.
- Write new content to files.
- Append content without replacing existing data.
- Use the
withstatement safely. - Understand text and binary files.
- Control file positions using
seek(). - Handle common file-related errors.
- Work with files and folders in practical programs.
What Is File Handling?
File handling means using a program to create, read, modify, or manage files stored on a computer.
Files allow information to remain available even after your Python program stops running.
A normal Python variable exists in memory while your program is running. A file can store information so that another program execution can read it later.
Example
name = "Ali"
with open("student.txt", "w") as file:
file.write(name)
This creates or replaces student.txt and stores
the student's name inside it.
Why Files Matter
Files are useful whenever information needs to survive after the program finishes.
Examples include:
- Saving customer information.
- Storing application settings.
- Saving reports.
- Keeping logs.
- Reading configuration data.
- Importing datasets.
- Exporting results.
- Storing notes and text.
Python Program
↓
Write Data
↓
File
↓
Read Later
↓
Python Program
Common File Types
Python can work with many types of files.
.txt → Text files
.csv → Spreadsheet-style data
.json → Structured data
.py → Python source code
.log → Log files
.jpg → Image file
.png → Image file
.pdf → Document file
Different file formats require different techniques. In this lesson, we focus primarily on text file handling.
CSV and JSON files will be covered in more detail in later lessons.
The open() Function
Python provides the built-in open() function
for working with files.
Basic syntax
open(filename, mode)
For example:
file = open("notes.txt", "r")
This opens notes.txt in read mode.
When using open() directly, the file
should eventually be closed. The safer and preferred
approach for normal file operations is the
with statement, which we will learn
later in this lesson.
File Modes
The mode tells Python what you intend to do with the file.
"r" Read
"w" Write
"a" Append
"x" Create
"b" Binary
"t" Text
Read mode
"r" opens a file for reading.
Write mode
"w" opens a file for writing. If the file
already exists, its previous contents are replaced.
Append mode
"a" adds new content to the end of an existing
file.
Create mode
"x" creates a new file and raises an error if
the file already exists.
Write mode can overwrite existing file contents. Always choose the mode based on what you actually want the program to do.
Reading a File
The read() method reads file content.
Python is powerful.
Python is readable.
Python is versatile.
with open("notes.txt", "r") as file:
content = file.read()
print(content)
Python is powerful.
Python is readable.
Python is versatile.
Without an argument, read() attempts to read
the remaining contents of the file.
Reading a specific number of characters
with open("notes.txt", "r") as file:
content = file.read(6)
print(content)
Python
readline()
The readline() method reads one line at a time.
with open("notes.txt", "r") as file:
first_line = file.readline()
print(first_line)
You can call readline() repeatedly to read
subsequent lines.
with open("notes.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
readlines()
The readlines() method reads the lines and
returns them as a list.
with open("notes.txt", "r") as file:
lines = file.readlines()
print(lines)
['Python is powerful.\n',
'Python is readable.\n',
'Python is versatile.']
Reading a very large file with
readlines() loads its lines into memory.
For large files, processing one line at a time is
often more efficient.
Looping Through a File
A file object can be iterated over directly.
with open("students.txt", "r") as file:
for line in file:
print(line.strip())
This is a useful technique for processing files line by line without loading the entire file into memory.
For large text files, line-by-line processing is often a good balance between simplicity and memory efficiency.
Writing to a File
Use "w" mode and the write()
method to write text to a file.
with open("message.txt", "w") as file:
file.write("Hello from PyLearn!")
If message.txt does not exist, Python creates
it.
If it already exists, its previous content is replaced.
Writing multiple pieces of text
with open("profile.txt", "w") as file:
file.write("Name: Ali\n")
file.write("Age: 25\n")
file.write("City: Multan\n")
Appending to a File
Use "a" mode when you want to add information
without deleting the existing content.
with open("activity.log", "a") as file:
file.write("User logged in\n")
If the file already contains:
User opened the application
User viewed dashboard
After appending, it may contain:
User opened the application
User viewed dashboard
User logged in
Append mode is especially useful for logs, activity records, notes, and event histories.
Writing Multiple Lines
The writelines() method can write multiple
strings from an iterable.
lines = [
"Ali\n",
"Sara\n",
"Ahmed\n"
]
with open("students.txt", "w") as file:
file.writelines(lines)
writelines() does not automatically
insert newline characters. If you want each item
on a separate line, include \n yourself.
The with Statement
The with statement is the preferred way to
handle ordinary Python file operations.
with open("notes.txt", "r") as file:
content = file.read()
print(content)
When the with block finishes, Python handles
closing the file automatically, including when an
exception occurs during the block.
Manual approach
file = open("notes.txt", "r")
content = file.read()
file.close()
Prefer with open(...) for normal
file operations. It makes resource management
safer and cleaner.
File Encoding
Text files store characters using an encoding. When working with text, explicitly specifying an encoding such as UTF-8 is often a good practice.
with open(
"message.txt",
"w",
encoding="utf-8"
) as file:
file.write("Hello Python! مرحبا")
You can also specify encoding when reading:
with open(
"message.txt",
"r",
encoding="utf-8"
) as file:
content = file.read()
Explicit encoding helps your application handle text consistently across different systems and languages.
Binary Files
Not every file contains ordinary text. Images, audio, videos, and many other formats contain binary data.
Python supports binary modes using b.
Reading binary data
with open("photo.jpg", "rb") as file:
data = file.read()
Writing binary data
with open("copy.jpg", "wb") as file:
file.write(data)
Use text mode for textual data and binary mode for binary content such as images and other non-text files.
File Position & seek()
When you read from a file, Python maintains a current position within that file.
The seek() method moves that position.
with open("notes.txt", "r") as file:
print(file.read(6))
file.seek(0)
print(file.read(6))
Python
Python
seek(0) moves the file position back to the
beginning.
tell()
The tell() method returns the current file
position.
with open("notes.txt", "r") as file:
print(file.tell())
file.read(6)
print(file.tell())
0
6
The exact position can depend on the file and how it is
opened, but the key idea is that tell() reports
the current position and seek() changes it.
Common File Errors
FileNotFoundError
Reading a file that does not exist can raise
FileNotFoundError.
with open("missing.txt", "r") as file:
content = file.read()
PermissionError
Python may raise PermissionError when the
operating system does not allow the requested operation.
IsADirectoryError
Attempting to open a directory as though it were a normal
file can raise IsADirectoryError.
Later, when you learn exception handling, you will
be able to use try and
except to handle expected file errors
gracefully.
Working with Files & Folders
Python's os and pathlib modules
provide tools for working with files and directories.
Using pathlib
pathlib provides an object-oriented approach
to filesystem paths.
from pathlib import Path
file_path = Path("notes.txt")
print(file_path.exists())
Creating a directory
from pathlib import Path
folder = Path("reports")
folder.mkdir(exist_ok=True)
Reading and writing with pathlib
from pathlib import Path
file = Path("report.txt")
file.write_text(
"Monthly sales report",
encoding="utf-8"
)
content = file.read_text(
encoding="utf-8"
)
print(content)
pathlib is often a clean and readable
choice for filesystem paths. You will encounter it
frequently in modern Python projects.
Real-World Examples
File handling becomes useful in many practical applications.
Example 1 — Application Log
message = "User opened the dashboard\n"
with open("app.log", "a", encoding="utf-8") as file:
file.write(message)
Example 2 — Student Records
Ali,85
Sara,92
Ahmed,78
A Python program can read these records and process them.
Example 3 — Saving a Report
report = """Sales Report
-------------
Total Orders: 125
Revenue: 450000
Top Product: Laptop
"""
with open("sales_report.txt", "w", encoding="utf-8") as file:
file.write(report)
Example 4 — Simple Notes Application
note = input("Enter a note: ")
with open("notes.txt", "a", encoding="utf-8") as file:
file.write(note + "\n")
print("Note saved successfully.")
This small program demonstrates a real persistence workflow: user input → file storage → future retrieval.
Common Mistakes
1. Using "w" when you meant "a"
Write mode replaces existing contents. Use append mode when you need to preserve existing data.
2. Forgetting the newline
write() does not automatically add a
new line. Use \n when appropriate.
3. Forgetting encoding
For text applications, explicitly using
encoding="utf-8" can make behavior
more predictable across systems.
4. Reading a missing file
Make sure the path is correct and handle expected missing-file situations appropriately.
5. Not using with
The with statement makes file resource
management safer and cleaner.
6. Using text mode for binary files
Images and other binary data should be handled using
binary modes such as rb and
wb.
Be deliberate about the file mode, path, encoding, and whether your program should replace, append, or simply read existing information.
Practice Exercises
Complete these exercises without copying the examples directly. Try to build each solution yourself.
Exercise 1 — Create a File
Create a file called welcome.txt and write
a welcome message inside it.
Exercise 2 — Read a File
Read welcome.txt and display its contents.
Exercise 3 — Student Names
Store five student names in a text file, one name per line, and then read them using a loop.
Exercise 4 — Append Notes
Ask the user for a note and append it to
notes.txt.
Exercise 5 — Word Counter
Read a text file and calculate the total number of words.
Exercise 6 — Line Counter
Read a file line by line and count how many lines it contains.
Exercise 7 — File Copy
Read a text file and create another file containing the same content.
Exercise 8 — pathlib
Use pathlib.Path to check whether a file
exists and display its file name.
Mini Challenge — Student Record Manager
Build a small command-line application that stores student records inside a text file.
Create a program that allows a user to add student records and view the saved records later.
Suggested file
students.txt
Each record could contain
Name: Ali
Age: 20
Marks: 85
----------------
Name: Sara
Age: 21
Marks: 92
----------------
Requirements
- Ask the user for a student's name.
- Ask for age.
- Ask for marks.
-
Save the record to
students.txt. - Use append mode so existing students are preserved.
- Add an option to display all saved students.
-
Use the
withstatement for file operations.
Bonus challenge
Add a search option that asks for a student's name and displays matching records from the file.
User input + strings + loops + conditions + file reading + file writing + file persistence.
Quick Knowledge Check
Test what you learned about Python file handling.
1. Which function is used to open a file?
2. Which mode is used for reading?
3. What does "w" mode do if the file already exists?
4. Which mode is normally used to append content?
5. Which method reads the entire remaining file content?
6. What is the main advantage of using with open()?
7. Which mode is appropriate for reading binary data?
8. What does seek(0) generally do?
9. Which method reports the current file position?
10. Which error can occur when a requested file does not exist?
Lesson Summary
File handling allows Python programs to store and retrieve information outside the program's temporary memory.
-
open()is used to open files. -
"r"is used for reading. -
"w"is used for writing and can replace existing content. -
"a"is used for appending. -
"x"creates a new file and fails if it already exists. -
read()reads file content. -
readline()reads one line. -
readlines()returns lines as a list. - Files can be processed line by line using loops.
-
write()writes text to a file. -
writelines()writes multiple strings. -
with open()is the preferred approach for ordinary file operations. - UTF-8 is a common text encoding.
-
Binary files use modes such as
rbandwb. -
seek()changes the file position. -
tell()reports the current position. -
pathlibprovides modern tools for filesystem paths.
You have now learned how Python programs can persist data using files. This is a major step toward building programs that work with real-world information.
In the next lesson, we will work with one of the most important data formats used by modern applications: JSON.
Ready for the Next Lesson?
Make sure you understand reading, writing, appending,
file modes, with, encoding, and basic
filesystem operations before continuing.