os.path 模块下 os.path.join()、os.path.exists()、os.path.split() 等基本函数用法介绍

os.path.isdir(path)

  • path(str),文件路径

判断 path 是否为文件夹目录,返回 True 或 False;

>>> os.listdir()
['map-location.xlsx', 'Map123.gif', 'recu_dir']
>>> os.path.isdir(os.getcwd() +'/Map123.gif')
False
>>> os.path.isdir(os.getcwd() +'/recu_dir')
True

os.path.join(path,name)

  • path(str),文件夹目录;
  • name(str),文件名;

通过 path + / + name 构建文件路径

>>> os.path.join('D:/ceshi','ceshi.txt')
'D:/ceshi\\ceshi.txt'

os.path.split(name)

  • name(str),文件路径;

将一个文件路径拆分为文件夹目录和文件名

>>> os.path.split('D:/ceshi/ceshi.txt')
('D:/ceshi', 'ceshi.txt')

os.path.exists(path)

  • path(str),文件路径或文件夹目录;

判断文件路径 path 是否存在,返回 True 或 False;

>>> os.path.exists(os.getcwd() +'/recu_dir')
True
>>> os.path.exists(os.getcwd() +'/recu_dir1')
False

os.path.isfile(path)

  • path(str),文件路径或文件夹目录

判断文件 path 是否为文件,返回 True 或 False;

>>> os.listdir()
['map-location.xlsx', 'Map123.gif', 'recu_dir']
>>> os.path.isfile(os.getcwd() +'/recu_dir')
False
>>> os.path.isfile(os.getcwd() +'/Map123.gif')
True

os.path.isdir(path)

  • path(str),文件路径

判断文件路径 path 知否为文件夹目录,返回 True 或 False;

>>> os.listdir()
>>> os.path.isdir(os.getcwd() +'/recu_dir')
True

os.path.isabs(path)

  • name(str),文件路径

判断文件路径 path 是否为绝对路径,返回 True, 或 False;

绝对路径 表示为完整路径 例如D:/Working/wor.txt相对路径 即表示相对某个文件下的文件路径,例如 ./word.txt

>>> os.path.isabs('D:/Working/1.png')
True
>>> os.path.isabs('a.png')
False
>>>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容