Python 3 – os.link() Method
In Python, there are several modules that allow you to interact with the operating system. One of such modules is ‘os’. With the ‘os’ module, you can perform various operations like listing files/directories, renaming files/directories, creating directories, and so on.
In this article, we’ll discuss the ‘os.link()’ method. This method creates a new hardlink for the file or directory src at dst. This method is not available on all operating systems. You can check if it’s available on your operating system by running the following code.
import os
if hasattr(os, "link"):
print("link() is available")
else:
print("link() is not available")
Syntax
os.link(src, dst)
Parameter
- src − This is the source file path to link.
-
dst − This is the destination file path.
Return Value
This method does not return any value.
Example 1: Create a Hardlink
Let’s see an example of how to create a hardlink using the ‘os.link()’ method.
import os
# Create a file with content 'Hello World'
with open("src.txt", "w") as file:
file.write("Hello World")
# Create a hard link for src.txt as dst.txt
os.link("src.txt", "dst.txt")
In the above example, we’ve created a file called ‘src.txt’ and wrote ‘Hello World’ to it. Then we’ve created a hardlink for ‘src.txt’ as ‘dst.txt’. Now if you modify the content of ‘src.txt’, you’ll notice that the content of ‘dst.txt’ also gets updated as both files point to the same inode.
Example 2: Create a Hardlink for a Directory
You can also create a hardlink for a directory.
import os
# Create a directory
os.mkdir("src")
# Create a hard link for src as dst
os.link("src", "dst")
In the above example, we’ve created a directory ‘src’ and then created a hardlink for it as ‘dst’. Now if you create a file inside ‘src’, it will be visible inside ‘dst’ since both directories point to the same inode.
Example 3: Error Handling
If you try to create a hardlink to a non-existent file or directory, you’ll get a ‘FileNotFoundError’.
import os
# Try to create a hard link for non-existent file
try:
os.link("non-existent-file.txt", "dst.txt")
except FileNotFoundError as e:
print(str(e))
# Try to create a hard link for non-existent directory
try:
os.link("non-existent-dir", "dst")
except FileNotFoundError as e:
print(str(e))
In the above example, we’ve intentionally tried to create a hardlink for a non-existent file and directory, resulting in a ‘FileNotFoundError’.
Conclusion
In this article, we’ve discussed the ‘os.link()’ method in Python. It allows you to create a new hardlink for the file or directory src at dst. This method is not available on all operating systems. We’ve also discussed how to create a hardlink for a file and a directory and how to handle errors if the file or directory does not exist.