import os
os.path.abspath(file) :返回文件所在的绝对路径
![](https://img.haomeiwen.com/i3012096/13b9aaa60a00dd75.png)
os.path.basename(path) :去掉目录路径,单独返回文件名
![](https://img.haomeiwen.com/i3012096/97e1c8b0c7d46961.png)
os.path.dirname(path) :去掉文件名,单独返回路径名
![](https://img.haomeiwen.com/i3012096/40fea676d3e41514.png)
os.path.commonprefix(list) :返回list(多个路径)中,所有path共有的最长的路径
![](https://img.haomeiwen.com/i3012096/014731e5361bd630.png)
os.path.join(path1[, path2[, ...]]) :把目录和文件名合成一个路径
![](https://img.haomeiwen.com/i3012096/a9bc157c06c532ed.png)
os.path.normcase(path) :转换path的大小写和斜杠
![](https://img.haomeiwen.com/i3012096/068df1c09c81b57e.png)
os.path.realpath(file) :返回文件的真实路径
![](https://img.haomeiwen.com/i3012096/ad0c20f1bd790b69.png)
os.path.split(path) :把路径分割成路径和文件名,返回一个元组
![](https://img.haomeiwen.com/i3012096/1ff5719653fc860a.png)
os.path.splitext(path) :分离文件名与扩展名,返回一个元组
![](https://img.haomeiwen.com/i3012096/99d3ba2edab9080e.png)
os.path.relpath(path[, start]) :从start开始计算相对路径
![](https://img.haomeiwen.com/i3012096/4660eb14c45d6df6.png)
os.path.expanduser(path) :把path中包含的"~"和"~user"转换成用户目录os.path.expandvars(path) :根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.getatime(path) :返回最后一次进入此path的时间(浮点型的秒数)
![](https://img.haomeiwen.com/i3012096/544f01ec77efae36.png)
os.path.getmtime(path) :返回在此path下最后一次修改的时间(浮点型的秒数)
os.path.getctime(path) :返回path下文件或目录创建时间(浮点型的秒数)
os.path.getsize(file) :返回文件大小(单位:字节),如果文件不存在就返回错误
![](https://img.haomeiwen.com/i3012096/b861bfa9f2c31fab.png)
os.path.exists(path) :路径存在则返回True,路径损坏返回False
os.path.lexists(path):路径存在则返回True,路径损坏也返回True
os.path.isabs(path) :判断是否为绝对路径
os.path.isfile(path) :判断路径是否为文件
os.path.isdir(path) :判断路径是否为目录
os.path.islink(path) :判断路径是否为链接
os.path.ismount(path) :判断路径是否为挂载点()
os.path.samefile(path1, path2) :判断目录或文件是否相同
如果以上方法中path这个参数写成 __file__的话,就代表是当前所执行的脚本。比如os.path.realpath(__file__) 就是返回当前所执行脚本的真实路径
![](https://img.haomeiwen.com/i3012096/5960601fc1ad5d3d.png)
简单考虑异常,使用某个目录或文件时,可以先判断它是否存在,如果不存在就创建一个
![](https://img.haomeiwen.com/i3012096/85a5364f351788f6.png)
参考链接:
https://blog.csdn.net/li1615882553/article/details/78759371
https://blog.csdn.net/qq_36387683/article/details/100145633
网友评论