python os.path.exists()方法,判断目录或路径是否存在

os.path.exists()方法

os.path.exists()是python标准库os方法,可用于判断参数指定的目录或文件的全路径是否存在。


os.path.exists()语法及参数

os.path.exsts( path )

提示:参数path可以是绝对路径,也可以是相对路径。


os.path.exists()返回值

python布尔bool类型值。如果参数指定path存在,os.path.exists()方法返回True,否则返回False。


os.path.exists()实例代码

提示:如下实例代码的运行和输出于Mac osx系统,如果是其它系统,请修改目录的格式:

>>> import os
>>> os.getcwd() #返回当前工作目录,备用
'/Users/z'
>>> os.makedirs('/Users/z/c/d') #递归创建目录,z包含c,c包含d
>>> os.path.exists('/Users/z/c') #参数为绝对路径
True
>>> os.path.exists('/Users/z/d') #z文件夹中并没有包含d,因此返回False
False
>>> os.path.exists('./c') #参数为相对路径,'.'表示当前目录,getcwd()返回的当前目录为'/Users/z'
True
>>> os.path.exists('./d')
False

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.