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)