Python 获取文件地址中的目录以及文件名

os.path. 获取文件目录及文件名

os.path.split(path)

Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty.

import os
path = r'E:\temp\CSDN'
print(os.path.split(path))
>> ('E:\\temp', 'CSDN')

os.path.dirname(path)
Returns the directory component of a pathname

import os
path = r'E:\temp\CSDN'
print(os.path.dirname(path))
>> E:\temp

os.path.basename(path)
Returns the final component of a pathname

import os
path = r'E:\temp\CSDN'
print(os.path.basename(path))
>> CSDN

os.path.splitext(path)
分离文件名与后缀

import os
filename = r'CSDN.exe'
print(os.path.splitext(filename))
>> ('CSDN', '.exe')

ntpath

ntpath.split(path)
Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty.

import ntpath
path = r'E:\temp\CSDN'
print(ntpath.split(path))
>> ('E:\\temp', 'CSDN')

ntpath.dirname(path)
Returns the directory component of a pathname

import ntpath
path = r'E:\temp\CSDN'
print(ntpath.dirname(path))
>> E:\temp

ntpath.basename(path)
Returns the final component of a pathname

import ntpath
path = r'E:\temp\CSDN'
print(ntpath.basename(path))
>> CSDN

ntpath.splitext(path)
分离文件名与后缀

import ntpath
filename = r'CSDN.exe'
print(ntpath.splitext(filename))
>> ('CSDN', '.exe')

版权声明:本文为weixin_43846270原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。