Python Read Files
Learn to read files in Python - Simple and easy for beginners!
π Let's Read Files!
Reading files is like opening a book! Python makes it super easy to get information from text files, data files, and more.
# Read a file - it's this simple!
with open('my_file.txt', 'r') as file:
content = file.read()
print(content)
4
Read Methods
Easy
To Learn
Safe
Operations
4 Ways to Read Files
read()
Reads entire file as one string
Whole file
Simple
readline()
Reads one line at a time
Line by line
Control
readlines()
Reads all lines into a list
List of lines
Easy access
for line in file
Loop through each line (best!)
Memory efficient
Recommended
Step 1: Create a Test File
Make a Simple Test File
# Create a simple test file
with open('test.txt', 'w') as file:
file.write('Line 1: Hello World!\n')
file.write('Line 2: Python is fun!\n')
file.write('Line 3: Reading files is easy!\n')
print("β
Test file created!")
Method 1: Read Whole File
Read Everything at Once
# Read the entire file
with open('test.txt', 'r') as file:
content = file.read()
print("π File content:")
print(content)
Read Only Part of File
# Read only first 10 characters
with open('test.txt', 'r') as file:
part = file.read(10)
print(f"First 10 chars: '{part}'")
Method 2: Read One Line
Read Line by Line
# Read one line at a time
with open('test.txt', 'r') as file:
line1 = file.readline()
line2 = file.readline()
print(f"First line: {line1.strip()}")
print(f"Second line: {line2.strip()}")
Read All Lines with Loop
# Read all lines using readline()
with open('test.txt', 'r') as file:
line_num = 1
while True:
line = file.readline()
if not line: # End of file
break
print(f"{line_num}: {line.strip()}")
line_num += 1
Method 3: Read All Lines as List
Get List of All Lines
# Read all lines into a list
with open('test.txt', 'r') as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
for i, line in enumerate(lines, 1):
print(f"{i}: {line.strip()}")
Clean Up the Lines
# Remove \n from lines
with open('test.txt', 'r') as file:
lines = file.readlines()
clean_lines = [line.strip() for line in lines]
print("Clean lines:")
for line in clean_lines:
print(f"β’ {line}")
Method 4: Loop Through File (Best Way!)
The Best Way - Loop Directly
# Best way - loop through file directly
with open('test.txt', 'r') as file:
for line_num, line in enumerate(file, 1):
print(f"{line_num}: {line.strip()}")
print("β
Done reading!")
π Why this is best:
- Uses less memory
- Works with huge files
- Clean and simple code
- Python professionals use this!
Read Files Safely
Handle Errors
# Safe way to read files
def read_file_safely(filename):
try:
with open(filename, 'r') as file:
content = file.read()
print(f"β
Read {filename} successfully!")
return content
except FileNotFoundError:
print(f"β File {filename} not found!")
except Exception as error:
print(f"β Error: {error}")
return None
# Test it
read_file_safely('test.txt')
read_file_safely('missing.txt')
File Encoding (Character Sets)
Specify Encoding
# Always specify encoding for text files
with open('test.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# Create file with special characters
with open('special.txt', 'w', encoding='utf-8') as file:
file.write('Hello! π CafΓ© naΓ―ve rΓ©sumΓ©')
# Read it back
with open('special.txt', 'r', encoding='utf-8') as file:
text = file.read()
print(f"Special text: {text}")
π‘ Common Encodings:
-
utf-8- Best choice (handles all characters) -
ascii- Basic English only -
latin-1- European characters
Reading CSV Files
Simple CSV Reading
import csv
# Create a simple CSV file
with open('data.csv', 'w') as file:
file.write('Name,Age,City\n')
file.write('Alice,25,New York\n')
file.write('Bob,30,London\n')
# Read CSV file
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
Reading JSON Files
Simple JSON Reading
import json
# Create a JSON file
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "coding"]
}
with open('person.json', 'w') as file:
json.dump(data, file)
# Read JSON file
with open('person.json', 'r') as file:
person = json.load(file)
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
print(f"Hobbies: {person['hobbies']}")
Reading Binary Files
Binary File Reading
# Create a binary file
binary_data = b"Hello in binary!"
with open('data.bin', 'wb') as file:
file.write(binary_data)
# Read binary file
with open('data.bin', 'rb') as file:
data = file.read()
print(f"Binary data: {data}")
print(f"As text: {data.decode()}")
Reading Large Files
Memory-Efficient Reading
# For large files, read line by line
def count_lines(filename):
count = 0
with open(filename, 'r') as file:
for line in file: # This doesn't load whole file!
count += 1
return count
# Create a bigger test file
with open('big_file.txt', 'w') as file:
for i in range(100):
file.write(f"This is line {i+1}\n")
lines = count_lines('big_file.txt')
print(f"File has {lines} lines")
Modern Way with pathlib
Using pathlib (Modern Python)
from pathlib import Path
# Create file
file_path = Path('modern.txt')
file_path.write_text('Hello from modern Python!')
# Read file
content = file_path.read_text()
print(f"Content: {content}")
# File info
print(f"File exists: {file_path.exists()}")
print(f"File size: {file_path.stat().st_size} bytes")
Quick Examples
Count Words in File
# Count words in a file
def count_words(filename):
word_count = 0
with open(filename, 'r') as file:
for line in file:
words = line.split()
word_count += len(words)
return word_count
# Test it
with open('story.txt', 'w') as file:
file.write('Once upon a time there was a Python programmer.')
words = count_words('story.txt')
print(f"Word count: {words}")
Find Text in File
# Find specific text in file
def find_in_file(filename, search_text):
with open(filename, 'r') as file:
for line_num, line in enumerate(file, 1):
if search_text in line:
print(f"Found '{search_text}' on line {line_num}: {line.strip()}")
# Test it
find_in_file('test.txt', 'Python')
π― Practice Time!
Build a Simple File Reader
# Simple file reader tool
def analyze_file(filename):
try:
with open(filename, 'r') as file:
lines = 0
words = 0
chars = 0
for line in file:
lines += 1
chars += len(line)
words += len(line.split())
print(f"π File Analysis: {filename}")
print(f" Lines: {lines}")
print(f" Words: {words}")
print(f" Characters: {chars}")
except FileNotFoundError:
print(f"β File {filename} not found!")
# Create test file
with open('sample.txt', 'w') as file:
file.write('Hello world!\nPython is awesome.\nFile reading is fun!')
# Analyze it
analyze_file('sample.txt')