Python中有join()和os.path.join()两个函数,具体作用如下:
join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
os.path.join(): 将多个路径组合后返回
join()函数
1. ‘sep’.join(seq)
参数:
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
2.os.path.join()函数
语法: os.path.join(path1[,path2[,……]])
返回值:将多个路径组合后返回
3.os.path.join()函数:连接两个或更多的路径名组件
- 如果各组件名首字母不包含’/’,则函数会自动加上
- 如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃
- 如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾
注意:若出现”./”开头的参数,会从”./”开头的参数的上一个参数开始拼接
import os
Path1 = 'a'
Path2 = 'b'
Path3 = 'c'
Path_n = Path1 + Path2 + Path3
Path_n1 = os.path.join(Path1,Path2,Path3)
print ('Path_n = ',Path_n)
print ('Path_n1 = ',Path_n1)
输出:
Path_n = abc
Path_n1 = a\b\c
import os
Path1 = '/a'
Path2 = 'b'
Path3 = 'c'
Path_n = Path1 + Path2 + Path3
Path_n1 = os.path.join(Path1,Path2,Path3)
print ('Path_n = ',Path_n)
print ('Path_n1 = ',Path_n1)
输出:
Path_n = /abc
Path_n1 = /a\b\c
import os
Path1 = 'a'
Path2 = '/b'
Path3 = 'c'
Path_n = Path1 + Path2 + Path3
Path_n1 = os.path.join(Path1,Path2,Path3)
print ('Path_n = ',Path_n)
print ('Path_n1 = ',Path_n1)
输出:
Path_n = a/bc
Path_n1 = /b\c
import os
Path1 = 'a'
Path2 = 'b'
Path3 = '/c'
Path_n = Path1 + Path2 + Path3
Path_n1 = os.path.join(Path1,Path2,Path3)
print ('Path_n = ',Path_n)
print ('Path_n1 = ',Path_n1)
输出:
Path_n = ab/c
Path_n1 = /c
import os
Path1 = 'a'
Path2 = './b'
Path3 = 'c'
Path_n = Path1 + Path2 + Path3
Path_n1 = os.path.join(Path1,Path2,Path3)
print ('Path_n = ',Path_n)
print ('Path_n1 = ',Path_n1)
输出:
Path_n = a./bc
Path_n1 = a/./b/c
参考链接:https://www.cnblogs.com/an-ning0920/p/10037790.html
参考链接:https://blog.csdn.net/fu6543210/article/details/80032895