脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 判断文件或目录是否存在的实例代码

Python 判断文件或目录是否存在的实例代码

2021-03-19 00:27Shocker Python

这篇文章主要介绍了Python 判断文件或目录是否存在的实例代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

使用 os 模块

判断文件是否存在

os.path.isfile(path)

判断目录是否存在

os.path.isdir(path)

判断路径是否存在

?
1
2
3
4
# 使用 path 模块
os.path.exists(path)
# 使用 access() 方法
os.access(path, os.F_OK)

使用 open 函数和异常捕获

如果直接用 open() 函数打开一个不存在的文件时,程序会抛出异常,我们可以通过 try 语句来捕获异常以达到判断文件是否存在的目的。

如果文件不存在,open() 函数会抛出 FileNotFoundError 异常。如果文件无操作权限,则会抛出 PersmissionError 异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
filePath = '/path/to/file'
try:
  file = open(filePath)
  file.close()
except FileNotFoundError:
  print("No such file or directory: '%s'" % filePath)
except IsADirectoryError:
  print("Is a directory: '%s'" % filePath)
except PermissionError:
  print("Permission denied: '%s'" % filePath)
else:
  print("File is exist: '%s'" % filePath)

使用 pathlib 模块

?
1
2
3
4
5
6
7
8
import pathlib
path = pathlib.Path('path/to/file')
# 判断路径是否存在
path.exists()
# 判断是否为文件
path.is_file()
# 判断是否为目录
path.is_dir()

总结

以上所述是小编给大家介绍的Python 判断文件或目录是否存在的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/shockerli/archive/2018/07/19/python-determine-file-exist.html

延伸 · 阅读

精彩推荐