Python Forum

Full Version: makin hardlinks with pathlib.Path
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i see that pathlib.Path.symlink_to exists and is documented. so, i can create a symlink. but i see no means to do a hardlink. i would have expected something named pathlib.Path.link_to to be there to be that. but it does not exist nor is anything like a hardlink documented for pathlib. it looks like i will need to use os.link to make the hardlinks. is there a known way to make a hardlink with just pathlib?
You can mokey patch.

import pathlib


def link(self, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True):
    os.link(self, dst, src_dir_fd=src_dir_fd, dst_dir_fd=dst_dir_fd, follow_symlinks=follow_symlinks)


pathlib.PosixPath.link = link
if you trace source code of pathlib
you will see that it actively uses os module. Internally, many methods of pathlib.Path class invokes
os.<some_method>. The latter (os), in turn, is based primarily on posixmodule.c.
So, it is possible to create hardlinks using pathlib (joke!), e.g.
import pathlib
pathlib.os.link(...) # will create hard link
... Unfortunately, I think, there is no way to do that the way you want.