如果你要确定文件存在的话然后做些什么,那么使用try是最好不过的

如果您不打算立即打开文件,则可以使用os.path.isfile检查文件

如果path是现有常规文件,则返回true。对于相同的路径,islink()和isfile()都可以为true

 

import os.path
os.path.isfile(fname)

如果你需要确定它是一个文件。

从Python 3.4开始,该pathlib模块提供了一种面向对象的方法(pathlib2在Python 2.7中向后移植):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

要检查目录,请执行以下操作:

 

 

if my_file.is_dir():
    # directory exists

要检查Path对象是否存在,不管它是文件还是目录,请使用exists():

 

 

if my_file.exists():
    # path exists

你也可以在一个try中使用resolve(strict=True):

 

 

try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists

 

作者:熊猫烧香

链接:www.pythonheidong.com/blog/article/15/

来源:python黑洞网

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!