Common file operations in Python, with examples and outputs.
- Opening and closing files
- Writing to files
- Reading from files
- Appending to files
- File and directory operations using the
os
module - Working with file paths
1. Opening and Closing Files
# Opening a file (creates it if it doesn't exist)
file = open('example.txt', 'w')
file.close()
# Using 'with' statement (automatically closes the file)
with open('example.txt', 'w') as file:
pass # File is automatically closed after this block
print("File opened and closed successfully.")
# Output: File opened and closed successfully.
2. Writing to Files
# Writing a single string
with open('example.txt', 'w') as file:
file.write("Hello, World!")
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('example.txt', 'w') as file:
file.writelines(lines)
print("Content written to file.")
# Output: Content written to file.
3. Reading from Files
# Reading entire file content
with open('example.txt', 'r') as file:
content = file.read()
print("File content:")
print(content)
# Output:
# File content:
# Line 1
# Line 2
# Line 3
# Reading file line by line
with open('example.txt', 'r') as file:
print("Reading line by line:")
for line in file:
print(line.strip()) # strip() removes leading/trailing whitespace
# Output:
# Reading line by line:
# Line 1
# Line 2
# Line 3
4. Appending to Files
# Appending content to an existing file
with open('example.txt', 'a') as file:
file.write("\nAppended line")
# Reading the updated content
with open('example.txt', 'r') as file:
content = file.read()
print("Updated file content:")
print(content)
# Output:
# Updated file content:
# Line 1
# Line 2
# Line 3
# Appended line
5. File and Directory Operations
import os
# Check if a file exists
file_exists = os.path.exists('example.txt')
print(f"Does 'example.txt' exist? {file_exists}")
# Output: Does 'example.txt' exist? True
# Get the current working directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
# Output: Current directory: /path/to/current/directory
# List files and directories
files_and_dirs = os.listdir()
print("Files and directories in current directory:")
for item in files_and_dirs[:5]: # Showing first 5 items
print(item)
# Output:
# Files and directories in current directory:
# example.txt
# some_directory
# another_file.py
# ...
# Create a new directory
os.mkdir('new_directory')
print("New directory created.")
# Output: New directory created.
# Rename a file
os.rename('example.txt', 'renamed_example.txt')
print("File renamed.")
# Output: File renamed.
# Remove a file
os.remove('renamed_example.txt')
print("File removed.")
# Output: File removed.
6. Working with File Paths
import os
# Join path components
path = os.path.join('directory', 'subdirectory', 'file.txt')
print(f"Joined path: {path}")
# Output: Joined path: directory/subdirectory/file.txt
# Get the base name of a path
base = os.path.basename(path)
print(f"Base name: {base}")
# Output: Base name: file.txt
# Get the directory name of a path
dir_name = os.path.dirname(path)
print(f"Directory name: {dir_name}")
# Output: Directory name: directory/subdirectory
# Split a path into directory and file
dir_path, file_name = os.path.split(path)
print(f"Directory: {dir_path}, File: {file_name}")
# Output: Directory: directory/subdirectory, File: file.txt
# Get file extension
_, extension = os.path.splitext(path)
print(f"File extension: {extension}")
# Output: File extension: .txt