API · Python
Python os.link() Method
The os.link() is an in-built Python function used to generate a hard link.
On this page
Python os.link() method is an efficient way of creating a duplicate of an existing file. This method creates a hard link that points to the source named destination.
Syntax of Python os.link() Method
os.link(source, destination)
Parameters
source |
It’s an address object of a file system path or a symlink for which the link will be generated. |
destination |
It’s an address object of a file system path or a symlink where the link will be generated. |
Return
In the execution process, this method does not return any value.
Example 1: Use the os.link() Method in Python
import os
source = "C:/Users/786/Documents/File.txt"
destination = "C:/Users/786/Desktop/NewFile.txt"
os.link(source, destination)
print("The hard link has been created successfully.")
Output:
The hard link has been created successfully.
An OSError might occur while using the os.link() method due to invalid or inaccessible processes and paths.
Example 2: Shorter Syntax of the os.link() Method
import os
os.link("C:/Users/786/Documents/File.txt", "C:/Users/786/Desktop/NewFile.txt")
print("The hard link has been created successfully.")
Output:
The hard link has been created successfully.
The os.link() method can support specifying src_dir_fd and dst_dir_fd to supply paths relative to directory descriptors, and not following symlinks.