File Handling
Reading from and writing to files in Python.
Opening Files
- Use open() function to open files.
- Modes: 'r' (read), 'w' (write), 'a' (append), 'r+' (read/write)
- Always close files with close() or use 'with' statement.
# Reading a file
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
# Better: using 'with' (auto-closes)
with open("data.txt", "r") as file:
content = file.read()
print(content)
# File automatically closed here
Reading Files
- read(): Read entire file
- readline(): Read one line
- readlines(): Read all lines into list
- Iterate over file object for line-by-line reading
# Read entire file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline
# Read all lines into list
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing Files
- 'w' mode: Creates new file or overwrites existing
- 'a' mode: Appends to existing file
- write(): Write string to file
- writelines(): Write list of strings
# Write to file (overwrites)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python is awesome!\n")
# Append to file
with open("output.txt", "a") as file:
file.write("This is appended\n")
# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
Working with Paths
- Use os.path or pathlib for file paths.
- Check if file exists before opening.
- Get file information (size, modification time).
import os
# Check if file exists
if os.path.exists("data.txt"):
print("File exists!")
# Get file size
size = os.path.getsize("data.txt")
print(f"File size: {size} bytes")
# List files in directory
files = os.listdir(".")
print(files)
# Join paths safely
path = os.path.join("folder", "subfolder", "file.txt")
Exception Handling
- Use try-except to handle file errors.
- Common errors: FileNotFoundError, PermissionError
- Always handle potential file operation failures.
# Safe file reading
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")