How to create hardlink of a file using Python?

Hard links in Python allow you to create multiple names for the same file on the filesystem. When you modify content through one link, changes are reflected in all other hard links since they point to the same data. Python provides several methods to create hard links programmatically.

Using os.link() Method

The most straightforward way to create a hard link in Python is using the os.link() method from the OS module. This method takes two arguments: the source file path and the destination hard link path.

Syntax

os.link(src, dst)

Parameters:

  • src ? Path to the existing source file
  • dst ? Path for the new hard link to be created

Example

The following example demonstrates creating a hard link with proper error handling ?

import os

# First create a sample file to demonstrate
with open('sample.txt', 'w') as f:
    f.write('This is sample content for hard link demo.')

# Specify the source file and hard link names
src = 'sample.txt'
dst = 'hardlink_sample.txt'

# Create the hard link
try:
    os.link(src, dst)
    print(f"Hard link created: {dst} -> {src}")
    
    # Verify both files exist and have same content
    with open(src, 'r') as f1, open(dst, 'r') as f2:
        print(f"Source content: {f1.read()}")
        print(f"Hard link content: {f2.read()}")
        
except FileExistsError:
    print(f"Error: The file '{dst}' already exists.")
except FileNotFoundError:
    print(f"Error: The source file '{src}' does not exist.")
except Exception as e:
    print(f"Error: {e}")
Hard link created: hardlink_sample.txt -> sample.txt
Source content: This is sample content for hard link demo.
Hard link content: This is sample content for hard link demo.

Using os.system() with Shell Command

You can create hard links by executing shell commands through Python. This method uses the Unix/Linux ln command to create hard links.

Example

The os.system() function executes shell commands directly ?

import os

# Create a sample file first
with open('document.txt', 'w') as f:
    f.write('Document content for shell command demo.')

# Specify source and destination
src = 'document.txt'
dst = 'shell_hardlink.txt'

# Create hard link using shell command
command = f'ln {src} {dst}'
result = os.system(command)

if result == 0:
    print(f"Hard link created using shell: {dst} -> {src}")
else:
    print("Error occurred while creating hard link")

# Verify the hard link
if os.path.exists(dst):
    print(f"Hard link exists: {os.path.exists(dst)}")
Hard link created using shell: shell_hardlink.txt -> document.txt
Hard link exists: True

Using subprocess.run() Method

The subprocess.run() method provides better control and error handling compared to os.system(). It allows secure execution of shell commands with detailed error information.

Example

Using subprocess provides better security and error handling ?

import subprocess
import os

# Create a sample file
with open('report.txt', 'w') as f:
    f.write('Report data for subprocess demo.')

# Specify source and destination
src = 'report.txt'
dst = 'subprocess_hardlink.txt'

# Create hard link using subprocess
try:
    result = subprocess.run(['ln', src, dst], check=True, capture_output=True, text=True)
    print(f"Hard link created using subprocess: {dst} -> {src}")
    
    # Check file stats to verify they are hard links
    src_stat = os.stat(src)
    dst_stat = os.stat(dst)
    print(f"Same inode number: {src_stat.st_ino == dst_stat.st_ino}")
    print(f"Link count: {src_stat.st_nlink}")
    
except subprocess.CalledProcessError as e:
    print(f"Command failed with return code {e.returncode}")
    print(f"Error output: {e.stderr}")
except FileNotFoundError:
    print("Error: 'ln' command not found (Windows system?)")
except Exception as e:
    print(f"Error: {e}")
Hard link created using subprocess: subprocess_hardlink.txt -> report.txt
Same inode number: True
Link count: 2

Comparison

Method Platform Error Handling Best For
os.link() Cross-platform Python exceptions Pure Python solution
os.system() Unix/Linux Basic return code Simple shell integration
subprocess.run() Unix/Linux Detailed error info Advanced shell control

Key Points

  • Hard links share the same inode and file content
  • os.link() is the recommended cross-platform method
  • Shell-based methods only work on Unix/Linux systems
  • Hard links cannot span different filesystems
  • Deleting one hard link doesn't affect others

Conclusion

Use os.link() for cross-platform hard link creation with proper Python exception handling. For Unix/Linux systems, subprocess.run() provides better control than os.system() when shell commands are needed.

Updated on: 2026-03-24T18:10:45+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements