os.path 模块中的 abspath(path) 方法用于获取提供的路径名路径的规范化绝对版本。
路径的规范化绝对版本只不过是一个修改后的字符串,它表示路径或文件,以便它符合目标操作系统上的有效路径格式。这涉及解析任何符号链接,如 “.” 和 “..”,并确保使用平台的正确路径分隔符(在类 Unix 系统上为 /,在 Windows 上为 \)正确分隔目录。
在处理文件路径以确保文件操作的一致性和准确性时,此方法特别有用。
语法
以下是该方法的语法 -
os.path.abspath(path)
参数
以下是其参数的详细信息 -
- path: 此参数表示类似路径的对象,它可以是表示文件系统路径的 string 或 bytes 对象,也可以是实现 os 的对象。PathLike 协议。
返回值
该方法返回一个字符串,该字符串表示所提供路径的绝对版本。
例子让我们探索一些示例来了解 os.path.abspath() 方法的工作原理。
例以下示例使用 os.path.abspath() 方法获取当前 script(file) 的完整路径。
# Import the os module
import os
# Getting the full path of the current script
result = os.path.abspath(__file__)
print(result)
print(type(result))
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
/home/cg/root/66260d93dc341/main.py
class 'str'>
class 'str'>
例
在这个例子中,os.path.abspath() 方法从包含段 “..” 的输入路径中获取规范化路径,通常这指的是父目录。
# Import the os module
import os
# Getting the normalized absolute path
path = 'mydir/../myfile.txt'
normalized_path = os.path.abspath(path)
# Display the normalizedpath
print(normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
/home/cg/root/66260f4adb57d/myfile.txt
例
在此示例中,路径提供给 os.path.abspath() 方法,其中 “.” 作为路径段,以获取规范化路径。
# Import the os module
import os
# Getting the normalized absolute path
path = 'mydir/./myfile.txt'
normalized_path = os.path.abspath(path)
print(normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
/home/cg/root/66260f4adb57d/mydir/myfile.txt
例
在以下示例中,os.path.abspath() 方法将包含双斜杠 “//” 的路径修改为单斜杠 “/”,并重新分配指向 “mydir” 目录中文件 “myfile.txt” 的绝对路径。
# Import the os module
import os
# Getting the normalized absolute path
path = 'mydir//myfile.txt'
normalized_path = os.path.abspath(path)
print(normalized_path)
输出
在我们的在线编译器中执行上述代码时,将获得以下输出 -
/home/cg/root/66260f4adb57d/mydir/myfile.txt