Python-路径拼接os.path.join()函数

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

 

 

  • 9
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值