Python| os.path.join() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中 OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.join()方法智能地连接一个或多个路径组件。此方法将各种路径组件与除了最后一个路径组件之外的每个非空部分之后的每个非空部分都使用一个目录分隔符 ('/') 连接。如果要加入的最后一个路径组件为空,则将目录分隔符 ('/') 放在末尾。
如果路径组件表示绝对路径,则所有先前连接的组件都将被丢弃,并从绝对路径组件继续连接。
Syntax: os.path.join(path, *paths)
Parameter:
path: A path-like object representing a file system path.
*path: A path-like object representing a file system path. It represents the path components to be joined.
A path-like object is either a string or bytes object representing a path.
Note: The special syntax *args (here *paths) in function definitions in python is used to pass a variable number of arguments to a function.
Return Type: This method returns a string which represents the concatenated path components.
代码:使用 os.path.join() 方法加入各种路径组件
Python3
# 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
/home/User/Desktop/file.txt
/home/file.txt
/home
/home/User/Public/Documents/
参考: https://docs。 Python.org/3/library/os.path.html