Python os.path.isdir()
Python中的os.path.isdir()方法用于检查指定的路径是否为现有目录。该方法遵循符号链接,这意味着如果指定的路径是指向目录的符号链接,那么该方法将返回True。
语法:os.path.isdir(path)
参数:
path:表示文件系统路径的类路径对象。
返回类型:此方法返回一个类bool的布尔值。如果指定的路径是现有目录,此方法返回True,否则返回False。
示例1
使用os.path.isdir()方法
# Python program to explain os.path.isdir() method
# importing os.path module
import os.path
# Path
path = '/home/User/Documents/file.txt'
# Check whether the
# specified path is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
# Path
path = '/home/User/Documents/'
# Check whether the
# specified path is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
输出:
False
True
示例2
如果指定的路径是符号链接
# Python program to explain os.path.isdir() method
# importing os.path module
import os.path
# Create a directory
# (in current working directory)
dirname = "GeeksForGeeks"
os.mkdir(dirname)
# Create a symbolic link
# pointing to above directory
symlink_path = "/home/User/Desktop/gfg"
os.symlink(dirname, symlink_path)
path = dirname
# Now, Check whether the
# specified path is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
path = symlink_path
# Check whether the
# specified path (which is a
# symbolic link ) is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
Output:
True
True