Python File Operations: Opening, Reading, Writing, and Directory Management
This guide explains how to open and close files, perform various read and write operations, and manage files and directories in Python using built‑in functions and the os, os.path, and shutil modules, with clear code examples for each task.
1. File Opening and Closing
Use the open function to obtain a file object. The basic syntax is file_object = open(file_name, mode) , where file_name is the path and mode can be 'r' (read), 'w' (write), 'a' (append), 'b' (binary), or '+' (read/write) possibly combined.
file_object = open(file_name, mode)
file_name: path and name of the file
mode: file opening mode, e.g., 'r', 'w', 'a', 'rb', 'w+', etc.Close the file with the close method, or preferably use a with statement to ensure automatic closure even if an exception occurs.
file_object.close()
with open('example.txt', 'r') as file:
content = file.read()
print(content)2. File Read and Write Operations
Reading functions:
read(): read the entire file content
readline(): read a single line
readlines(): read all lines and return a listExamples:
# Read entire file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Read line by line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
# Read all lines into a list
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)Writing functions:
write(): write a string to the file
writelines(): write a list of strings, each as a lineExamples:
# Write a single string
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
# Write multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open('example.txt', 'w') as file:
file.writelines(lines)3. File and Directory Operations
Creating directories with os.mkdir (single) or os.makedirs (nested):
import os
# Create a single directory
os.mkdir('new_directory')
# Create nested directories
os.makedirs('new_directory/sub_directory')Deleting directories with os.rmdir (empty) or shutil.rmtree (non‑empty):
import os
import shutil
# Delete an empty directory
os.rmdir('new_directory')
# Delete a non‑empty directory and its contents
shutil.rmtree('new_directory')Listing directory contents using os.listdir :
import os
# List all entries in the current directory
entries = os.listdir('.')
print(entries)Getting file information with os.path utilities:
import os
# Absolute path
file_path = os.path.abspath('example.txt')
print(file_path)
# Existence check
exists = os.path.exists('example.txt')
print(exists)
# File check
is_file = os.path.isfile('example.txt')
print(is_file)
# Directory check
is_dir = os.path.isdir('new_directory')
print(is_dir)
# File size
file_size = os.path.getsize('example.txt')
print(file_size)
# Last modification time
last_modified = os.path.getmtime('example.txt')
print(last_modified)Moving or renaming files with shutil.move :
import shutil
# Rename a file
shutil.move('old_name.txt', 'new_name.txt')
# Move a file
shutil.move('source_directory/old_name.txt', 'destination_directory/new_name.txt')Copying files with shutil.copy or entire directory trees with shutil.copytree :
import shutil
# Copy a single file
shutil.copy('source_file.txt', 'destination_file.txt')
# Copy an entire directory tree
shutil.copytree('source_directory', 'destination_directory')Conclusion
The article provides a comprehensive overview of Python file handling, covering opening and closing files, reading and writing data, and performing common file system operations such as creating, deleting, listing, moving, and copying files and directories.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.