Python os.link() Method

Python os.link() method is used to create a hard link pointing to a source file.

A hard link to a file is indistinguishable from the original directory entry.

Any changes to a file are effective regardless of the name used to open the file.

Deleting or renaming a hard link does not affect other hard links to the same file.

Syntax

os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)

Parameters

Name Description
src (string) The path to the source file.
dst (string) The path to the destination file. This is the name of the new hard link to be created.
src_dir_fd and dst_dir_fd (optional) File descriptors refer to directories (for relative paths).
follow_symlinks (optional, boolean) If False, and src is a symbolic link, a new link to the symbolic link itself will be created instead of the file pointed to by the symbolic link.

Return value

This method does not return any value.

Example 1: Basic usage

We will create a hard link to the “new_folder/data.txt” file.

Screenshot of before using os.link() method to create a hard link of the file

import os

# Creating a hard link for a file
os.link('new_folder/data.txt', 'new_folder/hard_link_to_source.txt')

print("Created hard link successfully")

Output

Created hard link successfully

Output of Python os.link() method

Example 2: Checking the effect of hard link

import os

# Creating a hard link for a file
os.link('new_folder/data.txt', 'new_folder/hard_link_to_source.txt')

with open('new_folder/data.txt', 'a') as file:
  file.write('This is the first line: New content')

# Reading from the hard link should show the same content
with open('new_folder/hard_link_to_source.txt', 'r') as file:
  print(file.read())

Output

This is the first line: New content

Screenshot of hard_link_to_source.txt file

Example 3: Error handling

import os

try:
  os.link('nonexistent_source_file.txt', 'new_hard_link.txt')
except FileNotFoundError as error:
  print(f"Error: {error}")

Output

Error: [Errno 2] No such file or directory: 'nonexistent_source_file.txt' -> 'new_hard_link.txt'

Example 4: Using file descriptors (Advanced)

import os

src_dir_fd = "your src file descriptor"
dst_dir_fd = "your src file descriptor"

# Assuming 'src_dir_fd' and 'dst_dir_fd' are file descriptors
# of relevant directories
os.link('new_folder/data.txt', 'hard_link_to_source.txt',
  src_dir_fd=src_dir_fd,
  dst_dir_fd=dst_dir_fd)

If your file descriptor paths are correct, you will get the proper output.

Hard links can be a powerful feature for file management and data organization, but it’s important to understand the underlying file system’s capabilities and limitations.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.