Python 检查文件是否存在:如何检查目录是否存在?
Python exists()
Python exists() 方法用于检查指定文件或目录是否存在。它还可以检查路径是否引用了任何打开的文件描述符。如果文件存在,它返回布尔值 True,否则返回 False。它与 os 模块和 os.path 子模块一起使用,形式为 os.path.exists(path)。
在本 Python 文件存在教程中,我们将学习如何使用 Python 确定文件(或目录)是否存在。要检查文件是否存在 Python,我们使用内置库 Python 检查文件是否存在函数。
有不同的方法可以验证文件或 Python 检查目录是否存在,使用如下列出的函数。
如何使用 os.path.exists() 检查 Python 中的文件是否存在
使用 path.exists,您可以快速检查文件或目录是否存在。以下是 Python 检查文件是否存在的步骤:
步骤 1) 导入 os.path 模块
在运行代码之前,重要的是导入 os.path 模块。
import os.path from os import path
步骤 2) 使用 path.exists() 函数
现在,使用 path.exists() 函数来 Python 检查文件是否存在。
path.exists("guru99.txt")
步骤 3) 运行以下代码
这是完整的代码
import os.path from os import path def main(): print ("File exists:"+str(path.exists('guru99.txt'))) print ("File exists:" + str(path.exists('career.guru99.txt'))) print ("directory exists:" + str(path.exists('myDirectory'))) if __name__== "__main__": main()
在本例中,只有文件 guru99.txt 在工作目录中创建
输出
File exists: True File exists: False directory exists: False
Python isfile()
Python isfile() 方法用于查找给定的路径是否为现有常规文件。如果指定路径是现有文件,则返回布尔值 True,否则返回 False。它可以通过以下语法使用:os.path.isfile(path)。
os.path.isfile()
我们可以使用 isfile 命令来检查给定的输入是否是文件。
import os.path from os import path def main(): print ("Is it File?" + str(path.isfile('guru99.txt'))) print ("Is it File?" + str(path.isfile('myDirectory'))) if __name__== "__main__": main()
输出
Is it File? True Is it File? False
os.path.isdir()
如果我们要确认给定的路径指向一个目录,我们可以使用 os.path.dir() 函数
import os.path from os import path def main(): print ("Is it Directory?" + str(path.isdir('guru99.txt'))) print ("Is it Directory?" + str(path.isdir('myDirectory'))) if __name__== "__main__": main()
输出
Is it Directory? False Is it Directory? True
pathlibPath.exists() (适用于 Python 3.4)
Python 3.4 及更高版本具有 pathlib 模块来处理文件系统路径。它使用面向对象的方法来 Python 检查文件夹是否存在。
import pathlib file = pathlib.Path("guru99.txt") if file.exists (): print ("File exist") else: print ("File not exist")
输出
File exist
完整代码
这是完整的代码
import os from os import path def main(): # Print the name of the OS print(os.name) #Check for item existence and type print("Item exists:" + str(path.exists("guru99.txt"))) print("Item is a file: " + str(path.isfile("guru99.txt"))) print("Item is a directory: " + str(path.isdir("guru99.txt"))) if __name__ == "__main__": main()
输出
Item exists: True Item is a file: True Item is a directory: False
如何检查文件是否存在
os.path.exists()
– 如果路径或目录存在,则返回True
。os.path.isfile()
– 如果路径是文件,则返回True
。os.path.isdir()
– 如果路径是目录,则返回True
。pathlib.Path.exists()
– 如果路径或目录存在,则返回True
。(在 Python 3.4 及更高版本中)