亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 检查文件是否存在 |如何在 Python 中检查目录是否存在

Python 存在()

Python 存在() 方法用于检查特定文件或目录是否存在。它还用于检查路径是否引用任何打开的文件描述符。如果文件存在则返回布尔值 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

输出:

文件存在:True
文件存在:False
目录存在: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()

输出:

是文件吗?是的
是文件吗?假的

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()

输出:

是目录吗?错
是目录吗?真的

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")

输出:

文件存在

完整代码

这是完整的代码

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()

输出:

项目存在:真
项目是文件:真
项目是目录:假

如何检查文件是否存在


Python

  1. Python 文件 I/O
  2. Python 目录和文件管理
  3. 如何在 Python 中获取当前日期和时间?
  4. 如何检查和校准湿度传感器
  5. Python Print() 语句:如何通过示例打印
  6. Python 换行:如何在 Python 中不使用换行进行打印
  7. Python JSON:编码(转储)、解码(加载)和读取 JSON 文件
  8. Python 平均值:如何在 Python 中找到列表的平均值
  9. Python - 环境设置
  10. Python - 文件 I/O
  11. 如何检查工业制动器
  12. 如何检查直流电机