OS Link Method in Python
Below are some examples by which we can understand about Python os link method:
Python OS Link Example
In this example, a hard link is created from the source file located at `/home/ihritik/file.txt` to a destination path `/home/ihritik/Desktop/file(link).txt`. After successfully creating the hard link, a confirmation message is printed.
Python3
import os src = '/home/ihritik/file.txt' # Destination file path dst = '/home/ihritik/Desktop/file(link).txt' os.link(src, dst) print ( "Hard link created successfully" ) |
Hard link created successfully
Checking the Existence of a File Before Creating a Hard Link
In this example, the script checks if a specified source file exists. If it does, a hard link is created to it at a given path; otherwise, an appropriate message is displayed indicating the file’s absence.
Python3
import os source_file = "path/to/source_file.txt" hard_link_path = "path/to/hard_link.txt" # Check if the source file exists before creating a hard link if os.path.exists(source_file): os.link(source_file, hard_link_path) print (f "Hard link created from {source_file} to {hard_link_path}" ) else : print (f "The source file {source_file} does not exist." ) |
The source file path/to/source_file.txt does not exist.
Python | os.link() method
os.link() method in Python is used to create a hard link. This method creates a hard link pointing to the source named destination. In this article, we will see what is os link and the uses of os.link().
Note: This method is only available on Windows and Unix platforms.