Python File Methods
Master file operations and data persistence in Python
📁 Working with Files
File handling is essential for reading data, saving results, and creating persistent applications. Python provides simple and powerful methods to work with files, from basic text files to complex data formats.
# Basic file operations
with open("data.txt", "w") as file:
file.write("Hello, World!")
with open("data.txt", "r") as file:
content = file.read()
print(content) # Hello, World!
File Method Categories
Reading Methods
Get data from files
file.read() # All content
file.readline() # One line
file.readlines() # List of lines
Writing Methods
Save data to files
file.write("text") # Write string
file.writelines(list) # Write list
file.flush() # Force write
Position Methods
Navigate within files
file.seek(0) # Go to position
file.tell() # Current position
file.rewind() # Go to start
Control Methods
Manage file state
file.close() # Close file
file.closed # Check if closed
file.mode # File mode
📖 Reading Methods
Different ways to read content from files
🔹 read() - Read All Content
# Read entire file at once
with open("story.txt", "r") as file:
content = file.read()
print(f"File content: {content}")
print(f"Content length: {len(content)} characters")
# Read specific number of characters
with open("story.txt", "r") as file:
first_10_chars = file.read(10)
print(f"First 10 characters: {first_10_chars}")
🔹 readline() - Read One Line
# Read one line at a time
with open("names.txt", "r") as file:
first_line = file.readline()
second_line = file.readline()
print(f"First name: {first_line.strip()}")
print(f"Second name: {second_line.strip()}")
# Read lines in a loop
with open("names.txt", "r") as file:
line_number = 1
while True:
line = file.readline()
if not line: # End of file
break
print(f"Line {line_number}: {line.strip()}")
line_number += 1
🔹 readlines() - Read All Lines
# Read all lines into a list
with open("shopping.txt", "r") as file:
items = file.readlines()
print("Shopping list:")
for i, item in enumerate(items, 1):
print(f"{i}. {item.strip()}")
# Process each line
with open("numbers.txt", "r") as file:
lines = file.readlines()
numbers = [int(line.strip()) for line in lines]
print(f"Sum of numbers: {sum(numbers)}")
✏️ Writing Methods
Different ways to write content to files
🔹 write() - Write String
# Write a single string
with open("output.txt", "w") as file:
file.write("Hello, World!")
file.write("\nThis is line 2")
# Write with formatting
name = "Alice"
age = 25
with open("profile.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
# Append to existing file
with open("log.txt", "a") as file:
file.write("New log entry\n")
🔹 writelines() - Write List of Strings
# Write multiple lines at once
fruits = ["apple\n", "banana\n", "cherry\n"]
with open("fruits.txt", "w") as file:
file.writelines(fruits)
# Write processed data
numbers = [1, 2, 3, 4, 5]
with open("squares.txt", "w") as file:
lines = [f"{n} squared is {n**2}\n" for n in numbers]
file.writelines(lines)
🔹 flush() - Force Write to Disk
# Ensure data is written immediately
with open("important.txt", "w") as file:
file.write("Critical data")
file.flush() # Force write to disk now
print("Data safely written!")
# Useful for real-time logging
import time
with open("realtime.log", "w") as file:
for i in range(5):
file.write(f"Event {i} at {time.time()}\n")
file.flush() # Write immediately
time.sleep(1)
🎯 Position Methods
Navigate and control position within files
🔹 seek() - Move to Position
# Move to specific position
with open("data.txt", "r") as file:
file.seek(0) # Go to beginning
first_char = file.read(1)
file.seek(5) # Go to position 5
next_chars = file.read(3)
print(f"First character: {first_char}")
print(f"Characters 5-7: {next_chars}")
# Go to end of file
with open("data.txt", "r") as file:
file.seek(0, 2) # 2 means from end
file_size = file.tell()
print(f"File size: {file_size} bytes")
🔹 tell() - Get Current Position
# Track position while reading
with open("story.txt", "r") as file:
print(f"Start position: {file.tell()}")
first_line = file.readline()
print(f"After first line: {file.tell()}")
file.read(10)
print(f"After reading 10 chars: {file.tell()}")
# Save and restore position
with open("data.txt", "r") as file:
saved_position = file.tell()
content = file.read(20)
file.seek(saved_position) # Go back
same_content = file.read(20)
print(f"Same content: {content == same_content}")
🔧 File Control Methods
Manage file state and properties
🔹 File Properties
# Check file properties
with open("example.txt", "r") as file:
print(f"File name: {file.name}")
print(f"File mode: {file.mode}")
print(f"Is closed: {file.closed}")
print(f"Is readable: {file.readable()}")
print(f"Is writable: {file.writable()}")
# After closing
print(f"After context: {file.closed}") # True
🔹 Manual File Handling
# Manual open/close (not recommended)
file = open("manual.txt", "w")
file.write("Manual handling")
print(f"Is closed: {file.closed}") # False
file.close()
print(f"Is closed: {file.closed}") # True
# Better: Use context manager
with open("auto.txt", "w") as file:
file.write("Automatic handling")
# File automatically closed here
📋 File Modes
Different ways to open files
📖 Reading Modes:
-
'r'- Read only (default) -
'rb'- Read binary
✏️ Writing Modes:
-
'w'- Write (overwrites) -
'wb'- Write binary -
'a'- Append
🔄 Read/Write Modes:
-
'r+'- Read and write -
'w+'- Write and read
# Different file modes
# Read mode
with open("data.txt", "r") as file:
content = file.read()
# Write mode (creates new or overwrites)
with open("output.txt", "w") as file:
file.write("New content")
# Append mode (adds to end)
with open("log.txt", "a") as file:
file.write("New log entry\n")
# Read and write mode
with open("data.txt", "r+") as file:
content = file.read()
file.write("\nAdded text")
# Binary mode for images, etc.
with open("image.jpg", "rb") as file:
binary_data = file.read()
print(f"File size: {len(binary_data)} bytes")
🛡️ Safe File Handling
Best practices for working with files
# Always use context managers
def safe_read_file(filename):
"""Safely read a file with error handling"""
try:
with open(filename, "r") as file:
return file.read()
except FileNotFoundError:
return f"File {filename} not found"
except PermissionError:
return f"No permission to read {filename}"
except Exception as e:
return f"Error reading file: {e}"
# Test the function
content = safe_read_file("example.txt")
print(content)
# Check if file exists before opening
import os
def process_file(filename):
"""Process file only if it exists"""
if os.path.exists(filename):
with open(filename, "r") as file:
lines = file.readlines()
print(f"File has {len(lines)} lines")
else:
print(f"File {filename} does not exist")
process_file("data.txt")
# Create backup before writing
def safe_write_file(filename, content):
"""Write file with backup"""
if os.path.exists(filename):
# Create backup
with open(filename, "r") as original:
backup_content = original.read()
with open(f"{filename}.backup", "w") as backup:
backup.write(backup_content)
# Write new content
with open(filename, "w") as file:
file.write(content)
print(f"File {filename} updated safely")
safe_write_file("important.txt", "New important data")