Python中的os.path.join和join的区别

概述

首先,这两个函数都是Python的系统函数,都有‘组合’、‘连接’之意,但是用法和应用场景千差万别。

函数说明

1、 join函数

首先来看一下官方的文档说明(这里以string.join()为例,其他的可以类推):
str.join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

歌词大意:

返回一个以str为连接符连接iterable里面的可迭代对象的字符串。如果在iterable中有任何一个非字符串元素,它会抛出一个TypeError异常,包括bytes对象。元素之间的分隔符就是调用这个join方法的str。

用法:

用于连接字符串数组。将字符串、元组、列表中的元素以指定的字符(即分隔符)连接成一个新的字符串。

语法:

str.join(iterable)
参数说明:str:分隔符,可以为空;iterable:要连接的元素序列、字符串、元组、字典等。

举个栗子:

对字符串进行操作:

In [1]: str1 = 'my name is XIAO_AI'

In [2]: print(':'.join(str1))
m:y: :n:a:m:e: :i:s: :X:I:A:O:_:A:I  

对元组进行操作:

In [3]: str2 = ('my', 'name', 'is', 'XIAO_AI')

In [4]: print(':'.join(str2))
my:name:is:XIAO_AI  

对序列(列表)进行操作:

In [6]: str3 = ['my', 'name', 'is', 'XIAO_AI']

In [7]: print(':'.join(str3))
my:name:is:XIAO_AI  

对字典进行操作:

In [8]: str4 = {'my': 'holy', 'name': 'jesus', 'is': 'chris'}

In [9]: print(':'.join(str4))
my:name:is  

对集合进行操作:

In [10]: str5 = {'my', 'name', 'is', 'XIAO_AI'}

In [11]: print(':'.join(str5))
is:name:my:XIAO_AI  

应用(九九乘法表):

In [12]: print('\n'.join([' '.join(['%s*%s=%-2s'%(y, x, x*y) for y in range(1, x+1)]) for x in range(1, 10)]))
1*1=1
1*2=2  2*2=4
1*3=3  2*3=6  3*3=9
1*4=4  2*4=8  3*4=12 4*4=16
1*5=5  2*5=10 3*5=15 4*5=20 5*5=25
1*6=6  2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7  2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8  2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9  2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

2、 os.path.join函数

同样的,我们先来看一下官方文档的说明:
os.path.join(path, *paths)
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

歌词大意:

这个函数能够将一个或多个子路径智能的合并在一起,返回值是包含将path和*path中的所有成员全部用一个文件连接符(os.sep)连接而成的一个字符串,当然了,如果最后一个元素为空,返回值会以一个文件连接符(分隔符)结尾。
如果当前子路径是一个绝对路径,所有之前的子路径将会被忽略,而会以当前这个绝对路径为开头连接接下来的子路径。

用法:

将多个子路径拼接后返回。

语法:

os.path.join(path, *paths)
返回值:将多个路径拼接后返回。

注意:会以最后一个绝对路径为返回值的起始路径。

举个栗子:

In [14]: import os

In [15]: os.path.join('/my/', 'name/is/', 'XIAO_AI')
Out[15]: '/my/name/is/XIAO_AI'

In [16]: os.path.join('/my/', 'name/is/', '/XIAO_AI')
Out[16]: '/XIAO_AI'

In [17]: os.path.join('/my/', '/name/is/', 'XIAO_AI')
Out[17]: '/name/is/XIAO_AI'

猜你喜欢

转载自blog.csdn.net/june_young_fan/article/details/80161355