Python| os.path.realpath() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.realpath()
方法用于通过消除路径中遇到的任何符号链接来获取指定文件名的规范路径。
Syntax: os.path.realpath(path)
Parameter:
path: A path-like object representing the file system path.
A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string value which represents the canonical path.
创建软链接或符号链接
在 Unix 或 Linux 中,可以使用 ln 命令创建软链接或符号链接。下面是在 shell 提示符下创建符号链接的语法:
$ ln -s {source-filename} {symbolic-filename}
例子:
例子:
在上面的输出中, “/home/ihritik/Desktop/file(shortcut).txt”是一个符号链接。
代码:使用 os.path.realpath() 方法获取规范路径并解析符号链接
# Python program to explain os.path.realpath() method
# importing os module
import os
# Path
path = "/home / ihritik / Desktop / file(shortcut).txt"
# Get the canonical path
# of the specified path
# by eliminating any symbolic links
# encountered in the path
real_path = os.path.realpath(path)
# Print the canonical path
print(real_path)
# Path
path = "/../../GeeksForGeeks / sample.py"
# Get the canonical path
# of the specified path
# eliminating any symbolic links
# encountered in the path
real_path = os.path.realpath(path)
# Print the canonical path
print(real_path)
# Path
path = "file.txt"
# Get the canonical path
# of the specified path
# eliminating any symbolic links
# encountered in the path
real_path = os.path.realpath(path)
# Print the canonical path
print(real_path)
os.chdir("/home / ihritik / Downloads/")
# Path
path = "file.txt"
# Get the canonical path
# of the specified path
# eliminating any symbolic links
# encountered in the path
real_path = os.path.realpath(path)
# Print the canonical path
print(real_path)
/home/ihritik/Documents/file(original).txt
/GeeksForGeeks/sample.py
/home/ihritik/file.txt
/home/ihritik/Downloads/file.txt
参考: https://docs。 Python.org/3/library/os.path.html