当前位置: 首页 > 科技观察

简单介绍os.path模块的常用方法

时间:2023-03-19 15:28:54 科技观察

os.path也是python中常用的模块,尤其是在处理文件系统的时候,涉及到文件和目录操作的时候经常用到。可以去一些框架的源码,编码的时候经常会用到这些方法。如果看官方文档,os.path大概提供了将近20个方法。其实我总结了9个比较常用的方法。您可以跟随并轻松记住它们。其实看方法名就可以知道方法是干什么的。os.path.png1,os.path.abspath获取文件的绝对路径path="test.py"print(os.path.abspath(path))#C:\Users\lzjun\workspace\python_scripts\test.py2,os.path.basename获取文件名,不包括目录部分。如果路径本身是目录,则返回空path="C:/Users/lzjun/workspace/python_scripts/test_path.py"print(os.path.basename(path))#test_path.pypath="../test/"print(os.path.basename(path))#emptystring3.os.path.dirname获取文件的目录部分,dirname+basename为文件的完整路径名path="C:/Users/lzjun/workspace/python_scripts/test_path.py"print(os.path.dirname(path))#C:/Users/lzjun/workspace/python_scripts4,os.path.exists判断路径是否存在。这里的路径包括目录和文件(在linux系统中,一切都是文件)。如果你直接复制我的代码,结果可能是False,因为你的系统可能没有这些目录。path="C:/Users/lzjun/workspace/python_scripts/test_path.py"print(os.path.exists(path))#Truepath="C:/Users/lzjun/workspace/python_scripts"print(os.path.exists(path))True5,os.path.getsize获取文件大小,也可以获取目录大小(所有文件),具体取决于你传的path参数是文件还是目录。单位是bytepath="C:/Users/lzjun/workspace/python_scripts/test_path.py"print(os.path.getsize(path))#1776,os.path.splitsplit方法会将路径分割成两部分,以最后一个斜线为切点,第一部分是文件所在的目录,第二部分是文件名本身。如果传入的路径以“/”结尾,那么第二部分是一个空字符串path="C:/Users/lzjun/workspace/python_scripts/test_path.py"print(os.path.split(path))#('C:/Users/lzjun/workspace/python_scripts','test_path.py')path="C:/Users/lzjun/workspace/python_scripts/"print(os.path.split(path))#('C:/users/lzjun/workspace/python_scripts','')7.os.path.joinjoin是split对应的方法,用于拼接文件路径。它通常用于已知文件的完整路径。我想结合它在同一个目录下创建一个b文件来使用join方法。a_path="C:/Users/lzjun/workspace/python_scripts/a.py"dir=os.path.split(a_path)[0]print(os.path.join(dir,"b.py"))#C:/Users/lzjun/workspace/python_scripts\b.py8,os.path.isdir判断路径是否为目录,注意如果目录不存在则不会报错,而是直接返回Falsepath="C:/Users/lzjun/workspace/python_scripts/"print(os.path.isdir(path))#True9.os.path.isfile判断路径是否为文件,注意如果文件不存在则不会报错,但是会直接返回Falseprint(os.path.isfile(__file__))#Truea_path="C:/Users/lzjun/workspace/python_scripts/a.py"print(os.path.isfile(a_path))#False(文件根本不存在)