Learn Python file handling with definitions, modes, and practical examples. Understand how to read, write, and manage files in Python with a complete code tutorial.
Working with files is a fundamental part of programming. Whether you’re saving user data, reading logs, or processing documents, Python provides powerful built-in functions for file handling.
In this guide, we’ll break down key terms, definitions, file modes, and practical examples, followed by a complete code demonstration.
File handling in Python refers to the ability to create, read, update, and delete files using built-in functions. Python provides the open() function as the primary tool for file operations.
2. Key Terms in File Handling
Before diving into code, let’s understand some important file-handling terms:
2.1 File
A file is a container that stores data (text, images, videos, etc.) on disk.
2.2 File Path
The location of a file in your system.
Example: C:/Users/John/Desktop/data.txt
2.3 File Modes
File modes define how a file is accessed:
"r" – Read (default). Opens file for reading.
"w" – Write. Creates or overwrites a file.
"a" – Append. Adds data at the end of the file.
"x" – Create. Creates a file, raises error if it exists.
"b" – Binary mode. Used for non-text files (images, videos).
"t" – Text mode (default).
2.4 File Pointer
A cursor that tracks your position in the file while reading or writing.
2.5 Buffering
Temporary storage while reading/writing to improve efficiency.
3. Opening and Closing Files
Use the open() function to open files.
file = open("example.txt", "r") # open in read mode
file.close() # close the file
? Best practice: Use with statement so files close automatically.
with open("example.txt", "r") as file:
data = file.read()
4. Reading Files in Python
4.1 Reading Entire File
with open("example.txt", "r") as file:
content = file.read()
print(content)
4.2 Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
4.3 Reading Fixed Number of Characters
with open("example.txt", "r") as file:
data = file.read(10) # reads first 10 characters
print(data)
5. Writing and Appending Files
5.1 Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, Python File Handling!\n")
5.2 Appending to a File
with open("example.txt", "a") as file:
file.write("This line was added later.\n")
6. Practical Full Code Example
Here’s a complete code snippet showing reading, writing, and appending in Python:
# File Handling Example in Python
# Step 1: Write data to a file
with open("mydata.txt", "w") as file:
file.write("Python File Handling Example\n")
file.write("This is the first line.\n")
# Step 2: Append more data
with open("mydata.txt", "a") as file:
file.write("This line is appended later.\n")
# Step 3: Read the file content
print("Reading file content:\n")
with open("mydata.txt", "r") as file:
for line in file:
print(line.strip())
Reading file content:
Python File Handling Example
This is the first line.
This line is appended later.
7. Python file modes with pros, cons, and best use cases.
File Mode
Definition
Pros
Cons
Best Use Case
"r"
Read mode (default). Opens file for reading only.
Safe, prevents accidental overwriting.
Error if file does not exist.
Reading configuration files, logs, or text documents.
"w"
Write mode. Creates a new file or overwrites existing content.
Quick way to start fresh.
Deletes existing data if file exists.
Creating new files or resetting content.
"a"
Append mode. Adds data at the end of a file.
Keeps existing data safe, just adds new content.
Cannot overwrite specific lines; only appends.
Adding logs, reports, or incremental updates.
"x"
Create mode. Creates new file, fails if file exists.
Prevents accidental overwriting.
Raises error if file already exists.
Creating unique files like reports or backups.
"b"
Binary mode. Reads/writes non-text files.
Handles images, videos, executables.
Harder to manipulate compared to text.
Processing images, audio, or binary data.
"t"
Text mode (default). Reads/writes text files.
Simple and human-readable.
Not suitable for binary data.
Working with text, CSV, JSON, or logs.
"+
Update mode. Allows both reading and writing.
Flexible: read and write in one file handle.
Complex to manage file pointer position.
Editing configuration files or mixed read/write tasks.
8. Actionable Instructions to Master File Handling
Practice each mode (r, w, a, x) to understand their behavior.
Use with statement to prevent memory leaks.
Work with real datasets like CSVs or logs.
Try error handling (try-except) to manage missing files.
Experiment with binary files (images, audio).
Conclusion
Python makes file handling simple and efficient with its built-in functions.
Use open() with appropriate modes.
Understand the difference between reading, writing, and appending.
Always prefer the with statement to manage resources.
By mastering file handling, you’ll unlock the ability to build real-world applications like log analyzers, text editors, and data processors.
Learn how garbage collection works in Python. You’ll learn the core ideas (reference counting and generational GC), explore the gc module, diagnose cyclic references, use weakref safely, and adopt practical patterns to keep memory usage healthy in real-world apps.
Learn Web Scraping with Python in 2025 with this complete step-by-step tutorial. Includes practical examples, code snippets, tools, and best practices for safe and efficient scraping.
This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy
These cookies are essential for the website to function properly.
These cookies help us understand how visitors interact with the website.
These cookies are used to deliver personalized advertisements.