📖 Reading Text Files
Python provides multiple ways to read text files. Understanding these methods is essential for data processing, configuration loading, and content analysis.
# Basic file reading
with open('example.txt', 'r') as file:
content = file.read()
print(content)
🎯 Reading Methods
Python offers several approaches to read text files.
Reading Entire Files
# Read entire file at once
filename = 'sample.txt'
# Read method - gets all content as string
with open(filename, 'r') as file:
content = file.read()
print(f"Entire file: {content[:50]}...")
# Readlines method - gets all lines as list
with open(filename, 'r') as file:
lines = file.readlines()
print(f"Number of lines: {len(lines)}")
if lines:
print(f"First line: {lines[0].strip()}")
print("File reading completed")
Line-by-Line Reading
# Memory efficient line-by-line reading
with open(filename, 'r') as file:
for line_num, line in enumerate(file, 1):
print(f"Line {line_num}: {line.strip()}")
if line_num >= 3: # Show first 3 lines only
break
print("Line-by-line reading completed")
Single Line Reading
# Read one line at a time
with open(filename, 'r') as file:
first_line = file.readline()
second_line = file.readline()
print(f"First: {first_line.strip()}")
print(f"Second: {second_line.strip()}")
print("Single line reading completed")
🔍 Advanced Reading Techniques
Python allows more sophisticated file reading operations.
File Existence and Encoding
import os
# Check if file exists before reading
filename = 'config.txt'
if os.path.exists(filename):
with open(filename, 'r') as file:
content = file.read()
print(f"File content: {content}")
else:
print("File not found")
print("File existence check completed")
Error Handling and Encoding
# Reading with encoding specification and error handling
try:
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
print(f"UTF-8 content: {content}")
except FileNotFoundError:
print("File not found")
except UnicodeDecodeError:
print("Encoding error")
print("Encoding-specific reading completed")
Partial Reading and Processing
# Reading specific number of characters
try:
with open(filename, 'r') as file:
chunk = file.read(100) # Read first 100 characters
print(f"First 100 chars: {chunk}")
except FileNotFoundError:
print("File not found")
# Skip empty lines and comments
def read_config_file(filename):
config_lines = []
try:
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if line and not line.startswith('#'):
config_lines.append(line)
return config_lines
except FileNotFoundError:
return []
config = read_config_file('config.txt')
print(f"Config lines: {config}")
📋 File Reading Reference Table
Method | Memory Usage | Best For | Returns |
---|---|---|---|
.read() | High | Small files | String |
.readline() | Low | Line-by-line processing | String |
.readlines() | Medium | All lines needed | List |
for line in file: | Low | Large files | Iterator |
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.