Python os.symlink() Method

Python os.symlink() method is used to create a symbolic link, often called a symlink or soft link. It creates a symbolic link pointing to a target file or directory.

A symbolic link is a file that serves as a reference or pointer to another file or directory. This differs from a hard link we created using the os.link() function; a symbolic link does not contain the data in the target file; it simply points to another file or directory.

Syntax

os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)

Parameters

Name Description
src (string) It is a path to the target file or directory to which the symbolic link will point.
dst (string) It is a path where the symbolic link will be created.
target_is_directory (boolean, optional) If True, and the target is a directory, a symbolic link to a directory is created
dir_fd (optional) A file descriptor refers to a directory.

Return value

This method does not return any value.

Example 1: Creating a symbolic link to a file

Before creating a symbolic link:

Screenshot before creating a symlink

import os

src = 'dir/file.txt'
dst = 'dir/symlink'

os.symlink(src, dst)

print(f"Symbolic link created from {dst} to {src}")

Output

Symbolic link created from dir/symlink to dir/file.txt

Output of os.symlink() function in Python

Example 2: Creating a Symbolic link to a directory

To create a symbolic link to a directory, pass the “target_is_directory=True” argument.

import os

src = 'dir'
dst = 'symlink'

os.symlink(src, dst, target_is_directory=True)

print(f"Symbolic link created from {dst} to {src}")

Output

Output of creating a symlink of a directory

Example 3: Error handling

import os

try:
  os.symlink('nonexistent_source', 'symlink')
except OSError as error:
  print(f"Error: {error}")

Output

Error: [Errno 17] File exists: 'nonexistent_source' -> 'symlink'

Since the source does not exist, it will throw the error.

Not all filesystems support symbolic links. Ensure that the underlying filesystem supports them.

Leave a Comment

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