Python provides a variety of tools for working with files and directories, from basic file I/O to higher-level operations like copying and renaming files. In this section, we will explore the different modules and functions available for file and directory access in Python.
os ModuleThe os module allows for basic operating system interaction like creating, renaming, and deleting files and directories.
import os
# Create a new directory
os.mkdir("new_directory")
# Rename a file
os.rename("old_file.txt", "new_file.txt")
# Delete a file
os.remove("file_to_delete.txt")
shutil ModuleThe shutil module provides higher-level file operations such as copying files and directories.
import shutil
# Copy a file
shutil.copy("file_to_copy.txt", "destination_folder")
# Copy a directory
shutil.copytree("directory_to_copy", "destination_folder")
open() FunctionTo open a file for reading or writing, Python provides the built-in open() function. This function returns a file object that can be used to access the contents of the file. The file can be opened in different modes such as read mode, write mode, and append mode.
# Open a file for reading
with open('example.txt', 'r') as file:
data = file.read()
# Open a file for writing
with open('new_file.txt', 'w') as file:
file.write('Hello, world!')
# Open a file for appending
with open('existing_file.txt', 'a') as file:
file.write('This text will be appended to the end of the file.')
os.path ModulePython also provides the os.path module, which allows for platform-independent manipulation of file paths. This module provides functions to join, split, and normalize file paths, among other things.
import os
# Join two paths
path = os.path.join("folder", "file.txt")
# Split a path into its directory and filename
directory, filename = os.path.split(path)
# Normalize a path
normalized_path = os.path.normpath(path)
glob ModuleIn addition to the os and shutil modules, Python also provides the glob module for finding files and directories that match a specified pattern. The glob function returns a list of file and directory paths that match the specified pattern.