Pathlib — The OOP Approach of Working with File System in Python (65/100 Days of Python)
The pathlib
module is a built-in module in Python 3 that provides an object-oriented way to handle files and directories. This module was introduced in Python 3.4 and provides a more convenient way to work with file paths than the traditional os.path
module.
Creating Path Objects With pathlib in Python
To create a path object, you can simply call the Path()
constructor and pass the path as a string. The constructor will automatically convert the string to the appropriate path object based on the operating system.
from pathlib import Path
# creating a path object
path = Path('my_folder/my_file.txt')
Accessing Parts of the Path
You can access various parts of the path using the attributes of the path object. For example, you can access the name of the file using the name
attribute and the directory of the file using the parent
attribute.
from pathlib import Path
path = Path('my_folder/my_file.txt') # creating a path object
print(path.name) # accessing the name of the file
print(path.parent) # accessing the directory of the file
Joining Paths
You can join paths using the /
operator. This is a convenient way to create paths that are relative to the current path.
from pathlib import Path
path = Path('my_folder') # creating a path object
new_path = path / 'my_file.txt' # joining paths
print(new_path) # printing the new path
Checking if a Path Exists
You can check if a path exists using the exists()
method. This method returns a boolean value indicating whether the path exists or not.
from pathlib import Path
# creating a path object
path = Path('my_folder/my_file.txt')
# checking if the path exists
if path.exists():
print('The path exists.')
else:
print('The path does not exist.')
Creating Directories
You can create a directory using the mkdir()
method. This method will create the directory if it does not exist. You can also use the mkdir()
method to create multiple directories at once.
from pathlib import Path
# creating a path object
path = Path('my_folder')
# creating the directory
path.mkdir()
# creating multiple directories
new_path = path / 'new_folder/sub_folder' # Or even path / 'new_folder' / 'sub_folder'
new_path.mkdir(parents=True)
Reading from Files
You can read the contents of a file using the read_text()
method. This method returns the contents of the file as a string:
from pathlib import Path
path = Path('my_folder/my_file.txt') # creating a path object
content = path.read_text() # reading the file
print(content) # printing the content of the file
So, instead of opening the file every time using the with open(...)
method, you can just read the contents of a file with read_text()
.
Writing to Files
You can write to a file using the write_text()
method. This method takes a string as input and writes it to the file.
from pathlib import Path
path = Path('my_folder/my_file.txt') # creating a path object
path.write_text('Hello, World!') # writing to the file
Creating Symlinks
Symbolic links, also known as symlinks, are special types of files in a file system that act as a pointer or reference to another file or directory.
When you create a symbolic link, it contains the path of the file or directory that it is pointing to, rather than containing the data of the file or directory itself. This means that when you access the symlink, the file system automatically redirects you to the actual file or directory that it is pointing to.
Symbolic links are commonly used to create shortcuts to files or directories located in other parts of the file system, or to reference frequently used files or directories with shorter and easier-to-remember names.
To create a symlink using pathlib
, you can use the symlink_to()
method. This method takes a path to the destination file or directory as an argument and creates a symlink in the current directory that points to the destination:
from pathlib import Path
destination_path = Path('/home/user/my_folder/my_file.txt') # Initial file
symlink_path = Path('my_symlink.txt') # Shortcut
symlink_path.symlink_to(destination_path) # creating the symlink
In the above example, we first create a path object for the destination file, which is located at /home/user/my_folder/my_file.txt
. We then create a path object for the symlink, which will be created in the current directory and will be named my_symlink.txt
. Finally, we use the symlink_to()
method of the symlink path object to create the symlink.
You can also create a symlink to a directory using the same method. Here is an example of how to create a symlink to a directory using pathlib
:
from pathlib import Path
destination_path = Path('/home/user/my_folder/') # Initial directory
symlink_path = Path('my_symlink_folder') # Shortcut
symlink_path.symlink_to(destination_path)
Similar to the example above, we created a symlink to the /home/user/my_filder
which can now be accessed with my_symlink folder
.
The pathlib
module provides a convenient and object-oriented way to handle files and directories in Python. It provides many useful methods for working with paths, creating directories, and reading and writing files. It is a great alternative to the traditional os.path
module and is recommended for all new projects in Python.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course
- Full series: 100 Days of Python
- Previous topic: Glob
- Next topic: Creating Custom Context Managers