Reading Files
Reading from Files
Python provides several methods to read data from files. The method you choose depends on how you want to process the file content - all at once, line by line, or in chunks.
Reading files is one of the most common file operations, used for processing data, reading configuration files, and loading saved information.
Reading Entire File
The read() method reads the entire file content as a string:
read_entire.py
# Read entire file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Read specific number of characters
with open("data.txt", "r") as file:
first_100 = file.read(100) # Read first 100 characters
print(first_100)
Reading Line by Line
Use readline() to read one line at a time, or readlines() to read all lines into a list:
read_lines.py
# Read one line at a time
with open("data.txt", "r") as file:
line1 = file.readline() # First line
line2 = file.readline() # Second line
print(line1)
print(line2)
# Read all lines into a list
with open("data.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # strip() removes newline
# Iterate directly over file (memory efficient)
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Processing File Content
Common patterns for processing file content:
processing.py
# Count lines in file
with open("data.txt", "r") as file:
line_count = len(file.readlines())
print(f"File has {line_count} lines")
# Find specific content
with open("data.txt", "r") as file:
for line in file:
if "Python" in line:
print(line.strip())
# Process CSV-like data
with open("scores.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
name, score = parts[0], parts[1]
print(f"{name}: {score}")
Best Practices
✅ Reading Files Tips
• Use read() for small files
• Use iteration for large files (memory efficient)
• Use strip() to remove newlines and whitespace
• Handle encoding issues with encoding parameter
• Check if file exists before reading (we'll learn error handling)
main.py
📤 Output
Click "Run" to execute...