Python中的OS模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。os.path模块是 Python 中 OS 模块的子模块,用于常见的路径名操作。
Python 中的os.path.join()方法智能地连接一个或多个路径组件。此方法将各个路径组件与除最后一个路径组件之外的每个非空部分后面的一个目录分隔符(“/”)连接起来。如果要连接的最后一个路径组件为空,则在末尾放置一个目录分隔符(“/”)。
如果路径组件表示绝对路径,则所有先前连接的组件都将被丢弃,并从绝对路径组件继续连接。``
语法: os.path.join(path, *paths)
参数:
path:表示文件系统路径的类路径对象。
path:表示文件系统路径的类路径对象。它表示要连接的路径组件。
类似路径的对象是表示路径的字符串或字节对象。
注意: Python 中函数定义中的特殊语法args(此处为 *paths)用于将可变数量的参数传递给函数。
返回类型:此方法返回一个表示串联路径组件的字符串。
`python
Python program to explain os.path.join() method
importing os module
import os
Path
path = “/home”
Join various path components
print(os.path.join(path, “User/Desktop”, “file.txt”))
Path
path = “User/Documents”
Join various path components
print(os.path.join(path, “/home”, “file.txt”))
In above example ‘/home’
represents an absolute path
so all previous components i.e User / Documents
are thrown away and joining continues
from the absolute path component i.e / home.
Path
path = “/User”
Join various path components
print(os.path.join(path, “Downloads”, “file.txt”, “/home”))
In above example ‘/User’ and ‘/home’
both represents an absolute path
but ‘/home’ is the last value
so all previous components before ‘/home’
will be discarded and joining will
continue from ‘/home’
Path
path = “/home”
Join various path components
print(os.path.join(path, “User/Public/”, “Documents”, “”))
In above example the last
path component is empty
so a directory separator (‘/’)
will be put at the end
along with the concatenated value