š Python File Handling ā Reading Files
Introduction š
Reading files is one of the most fundamental operations in Python. Python provides simple and powerful methods to read text files, JSON, CSV, logs, configs, and more.
Note
š” Always remember to close files after use ā or use with open() to do it automatically.
1. Opening a File for Reading š
You use the open() function:
open_file.py
file = open("data.txt", "r") # 'r' = read mode
content = file.read()
print(content)
file.close()Note
ā "r" = read mode (default)
2. Using with open() (Best Practice) š§
Using with automatically closes the file ā even if errors occur.
with_open.py
with open("data.txt", "r") as file:
content = file.read()
print(content)Note
ā Recommended for all file operations.
3. Reading Entire File at Once š
read_all.py
with open("data.txt", "r") as file:
data = file.read()
print(data)ā Useful for small files.
4. Reading File Line by Line š
read_line_by_line.py
with open("data.txt", "r") as file:
for line in file:
print(line.strip())ā Efficient for large files
ā strip() removes newline characters
5. Reading All Lines into a List š
readlines.py
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)ā Each line becomes an item in the list.
6. Reading a Specific Number of Characters āļø
read_chars.py
with open("data.txt", "r") as file:
chunk = file.read(10) # read first 10 characters
print(chunk)7. Reading One Line at a Time Using readline() š
readline.py
with open("data.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1, line2)8. Handling File Not Found Error ā ļø
file_not_found.py
try:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("ā File does not exist!")9. Reading Binary Files (Images, Videos, PDFs) š¼ļø
binary_read.py
with open("image.png", "rb") as file:
data = file.read()
print("Bytes read:", len(data))ā "rb" = read binary mode
10. Reading Files with Encoding (UTF-8, etc.) š
encoding.py
with open("data.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)11. Checking File Cursor Position š
tell_position.py
with open("data.txt", "r") as file:
print(file.tell()) # cursor position
file.read(5)
print(file.tell())12. Moving File Cursor Using seek() šļø
seek_example.py
with open("data.txt", "r") as file:
file.seek(0) # move to start
print(file.read(5))13. Real-World Example: Counting Lines š
count_lines.py
count = 0
with open("log.txt", "r") as file:
for _ in file:
count += 1
print("Total lines:", count)14. Real-World Example: Searching Text š
search_text.py
with open("notes.txt", "r") as file:
for line in file:
if "error" in line:
print("Found:", line.strip())15. Real-World Example: Reading Config Files āļø
config_read.py
settings = {}
with open("config.txt", "r") as file:
for line in file:
key, value = line.strip().split("=")
settings[key] = value
print(settings)Best Practices š”
- ā Always use with open() to avoid forgetting close()
- ā Handle exceptions for missing or locked files
- ā Avoid reading huge files into memory at once
- ā Use readline() or loops for large text files
Conclusion š
>>āReading files is the gateway to data ā logs, configs, documents, scripts, everything.ā āØ
You now fully understand how to Read Files in Python! Want the next topic? Try Write Files, Append Files, File Modes, or JSON Handling. Just tell me! š