Python os.link() Method

Python os.link() Method

  1. Syntax of Python os.link() Method
  2. Example 1: Use the os.link() Method in Python
  3. Example 2: Shorter Syntax of the os.link() Method

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.

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.

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.

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.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method