Python os.path.join() - 拼接一个或多个路径

Python os.path.join()

Python os.path.join() 方法智能拼接一个或多个路径组件。这个方法将各种路径组件连接起来,除了最后一个路径组件外,每个非空部分后面都有一个目录分隔符(‘ / ‘)。如果要连接的最后一个路径组件为空,则在末尾放置一个目录分隔符(‘ / ‘)。

如果一个路径组件表示一个绝对路径,那么之前连接的所有组件将被丢弃,连接将从绝对路径组件继续。

语法: os.path.join(path, *paths)

参数:

path:表示文件系统路径的类路径对象。

*paths:表示文件系统路径的类路径对象。它表示要连接的路径组件。

类路径对象是表示路径的字符串或字节对象。

注意:python函数定义中的特殊语法args(这里是*paths)用于向函数传递可变数量的参数。

返回类型: 这个方法返回一个表示连接的路径组件的字符串。

示例1

使用os.path.join()方法来连接各种路径组件

# 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/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程