The file system is a method and data structure that an operating system uses to manage files on disk drives. To manipulate these files (e.g., reading, writing, or deleting), Python provides a set of built-in functions and modules. In this section, we’ll deep dive into these operations.
os
ModulePython’s built-in os
module provides a way to use operating system dependent functionality, like reading or writing to the file system.
Creating Directories:
import os
os.mkdir("new_directory")
For creating deep directories, use os.makedirs()
:
os.makedirs("new_directory/sub_directory")
Listing Directories:
for dirpath, dirnames, filenames in os.walk("."):
print(f"Found directory: {dirpath}")
for file_name in filenames:
print(file_name)
Removing Directories:
os.rmdir("new_directory")
Use os.removedirs()
to remove multiple nested empty directories.
os
and shutil
Renaming Files:
os.rename("old_file.txt", "new_file.txt")
Removing Files:
os.remove("file_to_remove.txt")
Copying Files:
The shutil
module, also part of Python’s standard library, provides a higher-level file operations interface.
import shutil
shutil.copy("source.txt", "destination.txt")
Moving Files:
shutil.move("source.txt", "destination_folder/")
You can obtain meta-information about files using the os
module:
Checking if a File or Directory Exists:
print(os.path.exists("filename.txt")) # Returns True or False
Size of a File:
size = os.path.getsize("filename.txt")
Checking if a Path is a File or Directory:
os.path.isfile("filename.txt") # True if it's a file
os.path.isdir("directory_name") # True if it's a directory
The os.path
module provides methods to work with file paths:
Joining Paths:
It’s safer to use os.path.join()
to create paths as it ensures the correct path separators are used for the underlying operating system.
path = os.path.join("folder", "file.txt")
Splitting Paths:
head, tail = os.path.split("/path/to/file.txt")
print(head) # /path/to
print(tail) # file.txt
Python’s os
and shutil
modules offer a comprehensive suite of functions to manipulate the file system. These operations are crucial when automating tasks, managing datasets, or interacting with the underlying operating system. It’s essential to understand them thoroughly for various applications and scripts, ensuring smooth file operations across different platforms and environments.