Day 22 – Master Reading and Writing Text Files in Python | 60 Days Python Crash Course | ElectroLab

Reading and Writing Text Files in Python
Introduction
Working with files is one of the most essential skills for every Python programmer. It is used across almost all projects, from small scripts to large-scale applications. File handling becomes crucial when you need to store user input, maintain logs, analyze datasets, or exchange data between programs.
The ability to read and write text files in Python not only makes applications more powerful but also more practical for solving real-world challenges.
In this lesson, we will explore file operations in Python in detail. We will break down the fundamentals, show practical examples, discuss common pitfalls, and provide real-world applications. By the end, you will be confident in handling files efficiently, ensuring your programs are both reliable and scalable.
What You’ll Learn Today
- The fundamentals of file handling in Python.
- Different file modes and their purposes.
- How to read and write text files in Python with examples.
- Why
with open()
is the safest and recommended method. - Efficient techniques for handling very large files.
- Using absolute and relative file paths.
- Common mistakes and how to avoid them.
- Real-life applications of file handling.
- Practice questions, FAQs, and external resources.
What is File Handling?

File handling in Python allows programs to access and manipulate files stored on disk. These can include plain text files, configuration files, logs, or structured datasets. Python’s built-in functions and methods make it extremely simple to read and write text files in Python, often in just a few lines of code.
Learning this skill is important because almost every real-world Python project requires interaction with files.
Opening a File
file = open("example.txt", "r") # Open in read mode
- “r”: Read mode (default). File must exist.
- “w”: Write mode (creates new or overwrites existing file).
- “a”: Append mode (adds to file without deleting old content).
- “r+”: Read and write.
Using the correct mode ensures that your data is handled safely without unexpected overwriting.
Reading a File
with open("example.txt", "r") as file:
content = file.read()
print(content)
read()
: Reads the entire file into a single string.readline()
: Reads one line at a time.readlines()
: Reads all lines and returns them as a list.
Understanding how to read text files in Python is critical when working with input data, logs, or structured documents.
Writing to a File
with open("output.txt", "w") as file:
file.write("Hello, ElectroLab!\n")
file.write("Learning Python is fun.")
- Using
w
creates a new file or overwrites the existing one. - Using
a
appends new content without erasing old data.
Being able to write text files in Python enables you to save program results, logs, and processed datasets for future use.
Example: Appending Data
with open("output.txt", "a") as file:
file.write("\nThis line was added later.")
Appending ensures existing data is preserved, making it ideal for log files or incremental updates.
Reading Large Files Efficiently
Instead of loading a full file into memory:
with open("large_file.txt", "r") as file:
for line in file:
print(line.strip())
This method prevents memory overload and is the recommended approach when working with very large text files in Python.
File Paths
- Relative path:
open("data.txt")
– searches in the current working directory. - Absolute path:
open("C:/Users/Name/Desktop/data.txt")
– specifies the full path.
For cross-platform compatibility, Python’s os
and pathlib
modules make managing file paths more reliable.
Quizzes
- Which file mode allows adding new content without deleting the existing data?
- What is the key difference between
read()
andreadlines()
? - Why should
with open()
be used instead of onlyopen()
? - What happens if you open a file in
w
mode when it already exists?
FAQs
Q1: Can Python read binary files as well?
Yes, but you need to use rb
(read binary) or wb
(write binary).
Q2: How do I check if a file exists before opening it?
Use os.path.exists("filename.txt")
.
Q3: What happens if I try to open a non-existent file in read mode?
Python raises a FileNotFoundError
.
Q4: Can I write both text and numbers to a file?
Yes, but numbers must be converted to strings using str()
before writing.
Common Mistakes to Avoid
- Forgetting to close files when not using
with open()
. - Using
read()
on very large files, which can crash programs. - Accidentally overwriting files by using
w
instead ofa
. - Not handling
FileNotFoundError
with try-except. - Confusing binary and text modes when reading or writing.
Real-Life Uses of File Handling
- Log Files: Applications often write logs into text files for debugging.
- Data Storage: Text files and CSVs are widely used for structured data.
- Configuration Files: Store user preferences or program settings.
- Automation: Scripts can read data from files and save outputs automatically.
- IoT & Sensors: Recording sensor data in text files for later analysis.
Example – Writing Sensor Data to a File
with open("sensor_log.txt", "a") as file:
file.write("Temperature: 28°C\n")
This is a common example where programs are writing text files in Python to keep a running log of sensor readings.
Summary
Recap
- Python makes reading and writing text files in Python easy with
open()
. - Always prefer
with open()
for automatic file closing. - File modes (
r
,w
,a
,r+
) control how files are accessed. - Be careful with
w
mode to avoid unintentional data loss. - File handling powers essential applications like logging, configuration, and automation.
- Strong skills in reading and writing text files in Python prepare you for advanced programming tasks.
External Resources
Internal Links – Learn More with ElectroLab.in
- Day 1 – What is Python & Install IDE
- Day 2 – First Python Program: Print
- Day 8 – If-Elif-Else Statements
- Day 9 – For Loop in Python
- Day 21 – Exception Handling
For the complete Python Crash Course, visit: Learn Python – ElectroLab
What’s Next?
In the next lesson, we will explore Object-Oriented Programming (OOP) Basics.
You will learn about classes, objects, inheritance, and why OOP is the backbone of modern software development.