Learning how to work with paths, folders, and files
Working with files, directories, and pathnames in Python can be done using the os
and os.path
modules. These modules provide functionality for tasks such as navigating the file system, changing directories, checking the status of files and directories, and manipulating file paths.
Importing the Modules
To get started, we need to import the os
and os.path
modules:
import os import os.path
Working with Paths
os.path
module has several functions to manipulate file and directory paths:
os.path.join(path, *paths)
: joins one or more path components intelligently. This function can also handle any special characters in paths.
print(os.path.join("/home", "user", "file.txt")) # prints: /home/user/file.txt
os.path.abspath(path)
: returns the absolute version of a path.
print(os.path.abspath("file.txt")) # prints: /home/user/file.txt assuming you are in the /home/user directory
os.path.dirname(path)
: returns the directory name from the specified path.
print(os.path.dirname("/home/user/file.txt")) # prints: /home/user
os.path.basename(path)
: returns the base name from the specified path.
print(os.path.basename("/home/user/file.txt")) # prints: file.txt
Checking File or Directory Status
The os.path
module provides functions for checking whether a given path refers to an existing file or directory:
os.path.exists(path)
: checks if a path exists.
print(os.path.exists("/home/user/file.txt")) # prints: True if file.txt exists in /home/user
os.path.isfile(path)
: checks if a path is a file.
print(os.path.isfile("/home/user")) # prints: False
os.path.isdir(path)
: checks if a path is a directory.
print(os.path.isdir("/home/user")) # prints: True
Working with Directories
The os
module also provides functions to work with directories:
os.listdir(path)
: returns a list containing the names of the entries in the directory given by path.
print(os.listdir("/home/user")) # prints: ['file1.txt', 'file2.txt', 'dir1']
os.chdir(path)
: changes the current working directory to the given path.
os.chdir("/home/user")
os.getcwd()
: returns a string representing the current working directory.
print(os.getcwd()) # prints: /home/user assuming you are in the /home/user directory
os.mkdir(path)
: creates a directory at the specified path.
os.mkdir("/home/user/newdir")
In conclusion, Python’s os
and os.path
modules provide a set of tools for performing common tasks on directories and files, making it easier to create, update, read and delete files or directories. With these tools, Python becomes a powerful language for scripting and automating your system tasks.