文件操作系列之os.path模块

112 阅读2分钟

1 检查判断类的函数

这里以D:\workspace\Python_excerise目录

image-20220508163829123.png

1.1 检查路径是否存在

os.path.exists(path):判断path所指向的路径是否存在,存在则返回True,不存在返回False
print(os.path.exists(r'D:\workspace\Python_excerise'))

result:

True

1.2 检查路径是否是文件

os.path.isfile(path):判断path所指向的路径是否是文件,存在则返回True,不存在返回False
print(os.path.isfile(r'D:\workspace\Python_excerise'))

result:

False

1.3 检查文件是否是目录

os.path.isdir(path):判断path所指向的路径是否是目录,存在则返回True,不存在返回False
print(os.path.isdir(r'D:\workspace\Python_excerise'))

result:

True

1.4 检查路径是否为绝对路径

os.path.isabs(path):判断path所指向的路径件是否为绝对路径,是绝对路径则返回True,不是绝对路径则返回False
print(os.path.isabs(r'D:\workspace\Python_excerise'))

result:

True

2 路径操作类的函数

这里以D:\workspace\Python_excerise目录和D:\workspace\Python_excerise\README.md文件为例

image-20220508163829123.png

image-20220508164400761.png

2.1 获取绝对路径

os.path.abspath(path):获取path的绝对路径
print(os.path.abspath(r'README.md'))

result:

D:\workspace\Python_excerise\README.md

2.2 获取路径中的目录部分

os.path.dirname(path):获取path路径中的目录部分,返回最后一个分隔符之前的内容。

2.2.1 路径文文件时

print(os.path.dirname(r'D:\workspace\Python_excerise\README.md'))

result:

D:\workspace\Python_excerise

2.2.2 路径为目录时

print(os.path.dirname(r'D:\workspace\Python_excerise'))

result:

D:\workspace

2.3 获取路径中的基础名部分

os.path.basename(path):获取path路径中的基础名部分,返回最后一个分隔符之后的内容。

2.3.1 路径文文件时

print(os.path.basename(r'D:\workspace\Python_excerise\README.md'))

result:

README.md

2.3.2 路径为目录时

print(os.path.basename(r'D:\workspace\Python_excerise'))

result:

Python_excerise

2.4 分离文件名与目录

os.path.split(path):分离path路径的文件名与目录。该函数不会判断路径是否存在,都会进行分离。返回(os.path.dirname(path), os.path.basename(path))。

2.4.1 路径文文件时

print(os.path.split(r'D:\workspace\Python_excerise\README.md'))

result:

('D:\workspace\Python_excerise', 'README.md')

2.4.2 路径为目录时

print(os.path.split(r'D:\workspace\Python_excerise'))

result:

('D:\workspace', 'Python_excerise')

2.5 分离文件名和扩展名

os.path.splitext(path):分离分离path路径的文件名和扩展名,返回点号(.)之前的内容和点号之后的内容。当path为目录时,则返回的第二部分为空

2.5.1 路径文文件时

print(os.path.splitext(r'D:\workspace\Python_excerise\README.md'))

result:

('D:\workspace\Python_excerise\README', '.md')

2.5.2 路径为目录时

print(os.path.splitext(r'D:\workspace\Python_excerise'))

result:

('D:\workspace\Python_excerise', '')

2.5 拼接文件名与目录

os.path.join(dir, file):拼接目录dir与文件名file。与os.path.split()作用恰好相反

2.5.1 路径文文件时

print(os.path.join('D:\workspace\Python_excerise', 'README.md'))

result:

D:\workspace\Python_excerise\README.md

2.5.2 路径为目录时

print(os.path.join('D:\workspace', 'Python_excerise'))

result:

D:\workspace\Python_excerise