Pathlib#

Pathlib is a special library built into Python that makes it easier to work with paths in Python. This page is focused on usage of this library.

from pathlib import Path

Relative path#

You’re free to work with relative path.


The following cell demonstrates that you can call Path without any arguments to obtain an object that refers to the current directory.

relative_path = Path()
relative_path
PosixPath('.')

Using the resolve method of the Path class, you can obtain the corresponding absolute path.

relative_path.resolve()
PosixPath('/home/fedor/Documents/knowledge/python/basics/path/pathlib_files')

Here, we’ve simply obtained the path to the directory where this notebook is located.

Parent for “.”#

The parent attribute will refer to the same path as the object itself.


The following cell demonstrates that calling parent from . returns the same relative path, which corresponds to the same absolute path.

display(relative_path.parent)
display(relative_path.parent.resolve())
PosixPath('.')
PosixPath('/home/fedor/Documents/knowledge/python/basics/path/pathlib_files')

“..” path#

But by using .. as the path you’ll refer to the parent path of the current directory.


The following cell demonstrates that Path("..") corresponds to the parent directory’s absolute path. By combining multiple .. entries with the / operator, you can navigate to even deeper levels within the directory structure.

display(Path("..").resolve())
display(Path("../"*3).resolve())
PosixPath('/home/fedor/Documents/knowledge/python/basics/path')
PosixPath('/home/fedor/Documents/knowledge/python')

However, the parent attribute works in the conventional manner by removing sections of the path. It refers to absolute paths closer to the . path until it reaches the . directory.

display(Path("../..").parent)
display(Path("..").parent)
PosixPath('..')
PosixPath('.')

Manipulations#

There is a batch of methods of the Patholib.Path that allows manipulate fith filesystem. Some of them:

  • touch: create file.

  • mkdir: create folder.

  • unkink: delete file.

  • rmdir: for deleting empty directory.


The following cell shows the creation of a folder and a file within it.

dir_path = Path("example_directory")
dir_path.mkdir()
file_path = dir_path/"example_file"
file_path.touch()
!tree
.
├── example_directory
│   └── example_file
└── pathlib.ipynb

2 directories, 2 files

We can see the result using the system tree command.

The following cell shows the difference in applying the exists method to existing and non-existing paths.

print("This path exists", file_path.exists())
print("This path does not exists", file_path.exists())
This path exists False
This path does not exists False

Now it’s time for unlink and rmdir methods which removes file and folder we just created.

file_path.unlink()
dir_path.rmdir()
!tree
.
└── pathlib.ipynb

1 directory, 1 file

So there is only only this notebook in the output now.

Reading/writing#

You can use the pathlib library to read from or write to files located at a defined path. For this purpose, you can use the methods: write_text, read_text, write_bytes, or read_bytes.


The following cell saves the line hello to the "temp" path.

temp_path = Path("temp")
temp_path.write_text("hello")
!cat temp
hello

So, cut returns exactly the same line as we saved. Now let’s try to achieve the same result using the read_text method of the path.

print(temp_path.read_text())
temp_path.unlink()
hello

Now let’s try the write_bytes option. We can attempt to save an integer using the Path.write_bytes method.

integer_value = 1988

byte_length = (integer_value.bit_length() + 7) // 8
byte_representation = integer_value.to_bytes(byte_length, byteorder='little')

temp_path.write_bytes(byte_representation)
!cat temp
�

So cat have typical print for byte encoded values. Now read from the file and restore the number that was originally stored.

read_bytes = temp_path.read_bytes()
int_value = int.from_bytes(read_bytes, byteorder='little')
temp_path.unlink()

print(int_value)
1988

Overview#

There are a number of PosixPath methods that allow you to get information about your file/folder.

  • exists: check if file or folder exists.

  • iterdir: when the path points to a directory, yield path objects of the directory contents.


The following cell applies the exists method to a path that contains something and one that does not.

print(Path().exists())
print(Path("does_not_exists").exists())
True
False

The following cell applies the iterdir method to the parent directory of the current directory.

path = Path("..").resolve()
print("Files and folders in", path)
list(path.iterdir())
Files and folders in /home/fedor/Documents/knowledge/python/basics
[PosixPath('/home/fedor/Documents/knowledge/python/basics/files_folders.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/files_folders'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/regex'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/virtual_environment.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/logging_files'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/cli_arguments'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/cli_arguments.md'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/logging.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/syntax'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/build_package'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/build_package_files'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/build_package.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/unittest.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/logging'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/ipython_magics_files'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/data_classes.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/unittest'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/syntax.ipynb'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/datatypes'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/path_files'),
 PosixPath('/home/fedor/Documents/knowledge/python/basics/datatypes.ipynb')]