os.path.join()
os.path.join()
用来使用/
连接多个路径。如果最后一个路径组成部分是空的,那么将把/
放到最后。如果一个路径的组成部分是绝对路径,那么之前连接的路径都会被抛弃。
# 解释os.path.join()
# 导入模块
import os
# path
path = "/home"
# 连接各个路径
print(os.path.join(path, "User/Desktop", "file.txt"))
# Path
path = "User/Documents"
# 连接各个路径
print(os.path.join(path, "/home", "file.txt"))
# 在上边的例子,'/home'
# 代表绝对路径
# 所以在它之前组成的路径会被抛弃
# 重新在/home开始
# Path
path = "/User"
# 连接多个路径
print(os.path.join(path, "Downloads", "file.txt", "/home"))
# 在上边的例子,'/User' and '/home'
# 都是绝对路径
# 但是 '/home' 是最后一个
# 所以home之前的路径
# 将会抛弃,重新在/home开始连接
# Path
path = "/home"
# 连接多个路径
print(os.path.join(path, "User/Public/", "Documents", ""))
# 上边的例子,列表最后一个元素
# 是空的
# 所以会使用"/"作为参数连接在路径后边
/home\User/Desktop\file.txt
/home\file.txt
/home
/home\User/Public/Documents\
urllib.parse.urljoin(base, url)
官方解释:
Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter.
连接一个基本的URL和一个可能相对的URL,以形成对后者的一个绝对解释。
如果url是一个绝对URL(//,http://,https://),之前的会被抛弃
urljoin(‘https://www.google.com’, ‘//www.microsoft.com’)
‘https://www.microsoft.com’
否则二者会连接。
urlparse(‘http://a/b/c/d/e’)
ParseResult(scheme=‘http’, netloc=‘a’, path=’/b/c/d/e’, params=’’, query=’’, fragment=’’)urljoin(‘http://a/b/c/d/e’, ‘f’)
‘http://a/b/c/d/f’
urlparse(‘http://a/b/c/d/e/’)
ParseResult(scheme=‘http’, netloc=‘a’, path=’/b/c/d/e/’, params=’’, query=’’, fragment=’’)urljoin(‘http://a/b/c/d/e/’, ‘f’)
‘http://a/b/c/d/e/f’
如果url又/
urljoin(‘http://a/b/c/d/e’, ‘/f’)
‘http://a/f’