1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#from os import path import os.path path = '/home/vamei/doc/file.txt' print os.path.basename(path) print os.path.dirname(path) info = os.path.split(path) print info path2 = os.path.join( '/' , 'home' , 'vamei' , 'doc' , 'file1.txt' ) print path2 p_list = [path,path2] print p_list print os.path.commonprefix(p_list) print os.path.normpath(path2) |
正常输出结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from os import path #import os.path path = '/home/vamei/doc/file.txt' print path.basename(path) print path.dirname(path) info = path.split(path) print info path2 = path.join( '/' , 'home' , 'vamei' , 'doc' , 'file1.txt' ) print path2 p_list = [path,path2] print p_list print path.commonprefix(p_list) print path.normpath(path2) |
报错:AttributeError: 'str' object has no attribute 'basename'
是因为导入path和定义的path变量名称冲突了,把path变量换个名字就可以。
一般应该避免使用from..import而使用import语句,可以使程序更加易读,也可以避免名称的冲突。