Python os.path.realpath()
Python中的os.path.realpath()方法用于通过消除路径中遇到的任何符号链接来获取指定文件名的规范路径。
语法:os.path.realpath(path)
参数:
path:表示文件系统路径的类路径对象。
类路径对象是表示路径的字符串或字节对象。
返回类型:该方法返回一个表示规范路径的字符串值。
创建软链接或符号链接
在Unix或Linux中,可以使用ln命令创建软链接或符号链接。下面是在shell提示符下创建符号链接的语法:
$ ln -s {source-filename} {symbolic-filename}
示例:
在上面的输出中,“/home/ihritik/Desktop/file(快捷方式).txt”是一个符号链接。
示例1
使用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