Python| os.path.isdir() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.isdir()
方法用于检查指定路径是否为现有目录。此方法遵循符号链接,这意味着如果指定的路径是指向目录的符号链接,则该方法将返回 True。
Syntax: os.path.isdir(path)
Parameter:
path: A path-like object representing a file system path.
Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns 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)
输出:
True
True
参考: https://docs。 Python.org/3/library/os.path.html