Reading text files is an important skill in Python. It allows you to work with stored data such as reports, logs, configurations, and datasets.
Python provides built-in functions to open and read files easily.
OPENING A FILE
To read a file, use the open() function.
file = open("example.txt", "r")
• "example.txt" → File name
• "r" → Read mode
After opening the file, you can read its content.
READING FILE CONTENT
1. read() – Reads the entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
2. readline() – Reads one line at a time
file = open("example.txt", "r")
line = file.readline()
print(line)
file.close()
3. readlines() – Reads all lines into a list
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()
USING WITH STATEMENT (BEST PRACTICE)
Using with automatically closes the file after use.
with open("example.txt", "r") as file:
content = file.read()
print(content)
This is the recommended way to handle files.
READING FILE LINE BY LINE
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
.strip() removes extra spaces or newline characters.
FILE MODES
• "r" → Read (default)
• "w" → Write (overwrites file)
• "a" → Append
• "x" → Create new file
HANDLING FILE NOT FOUND ERROR
try:
with open("example.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found.")
IMPORTANT POINTS
• Always close the file (or use with)
• Use try-except to handle errors
• Read large files line by line to save memory
WHY FILE READING IS IMPORTANT
• Used in data analysis
• Used in report generation
• Important for automation
• Required in real-world applications
Understanding how to read text files is essential for working with external data in Python.