[파이썬] os `os.readlink()`로 심볼릭 링크 타겟 조회

In Python, the os module provides a convenient way to access and manipulate files and directories. One useful function in this module is os.readlink(), which allows you to retrieve the target of a symbolic link.

Symbolic links, also known as symlinks, are special files that act as pointers to another file or directory. They provide a way to create shortcuts or aliases for files and directories. With os.readlink(), you can easily determine the path of the actual file or directory that a symbolic link is pointing to.

Here’s an example of how you can use os.readlink() in Python:

import os

# Specify the path of the symbolic link
link_path = "/path/to/symlink"

try:
    # Get the target of the symbolic link
    target_path = os.readlink(link_path)

    print(f"The symbolic link at {link_path} is pointing to {target_path}")
except (OSError, FileNotFound) as e:
    print(f"Failed to read symbolic link: {e}")

In this example, we first import the os module. Then, we define the path of the symbolic link we want to inspect using the link_path variable. Inside a try-except block, we call os.readlink() with link_path as its argument to retrieve the target path of the symbolic link. If successful, we print a message displaying the link path and the target path. If an error occurs, such as the specified path not being a symbolic link or the link not existing, we catch the exception and print an error message.

It’s worth noting that os.readlink() raises an OSError if the specified path is not a symbolic link or if the link doesn’t exist. Additionally, FileNotFoundError is raised if the specified path cannot be found.

By using os.readlink(), you can easily retrieve the target of a symbolic link in Python, allowing you to perform further operations on the actual file or directory it points to.