Welcome to Day 41 of your Python journey!
Working with files is a core skill for any developer. Whether you're handling logs, reading configurations, or processing data, Python’s built-in open() function makes it simple and powerful.
Today, we’ll learn how to read files safely and efficiently using open().
📥 1. The open() Function Basics
The syntax is:
file = open("filename.txt", "mode")
-
"r"– Read mode (default) -
"w"– Write mode (overwrites file) -
"a"– Append mode -
"b"– Binary mode (use with images, etc.) -
"t"– Text mode (default)
Always remember to close files when done:
file = open("sample.txt", "r")
content = file.read()
file.close()
📄 2. Reading the Whole File
with open("sample.txt", "r") as f:
data = f.read()
print(data)
✅ Using with automatically closes the file, even if an error occurs.
📜 3. Reading Line by Line
readline() – Reads one line at a time:
with open("sample.txt", "r") as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()
readlines() – Returns all lines as a list:
with open("sample.txt", "r") as f:
lines = f.readlines()
print(lines)
📏 4. Reading Fixed Amount of Characters
with open("sample.txt", "r") as f:
first_10_chars = f.read(10)
print(first_10_chars)
🔄 5. Iterating Over a File Object
You can loop through a file directly:
with open("sample.txt", "r") as f:
for line in f:
print(line.strip())
This is memory-efficient for large files because it reads line by line.
🧨 6. Handling Errors Safely
Always handle exceptions when dealing with files:
try:
with open("non_existent.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("File not found!")
except IOError:
print("Error reading file!")
🛠️ Real-World Example: Count Words in a File
with open("sample.txt", "r") as f:
text = f.read()
words = text.split()
print("Total Words:", len(words))
📌 Summary
- Use
open(filename, "r")to read files. - Always close files or use
with open()for safety. -
read(),readline(), andreadlines()give you flexibility. - Handle errors with
try-except. - Iterating over file objects is memory-efficient for large files.
🧪 Practice Challenge
- Read a file and count:
- Total lines
- Total words
- Total characters
- Write a script to read a large log file and only print lines containing the word
"ERROR". - Read a file and reverse the order of its lines before printing.
- Write a script to read a large log file and only print lines containing the word
Top comments (0)