如何无异常地检查文件是否存在? [英] How do I check whether a file exists without exceptions?

查看:17
本文介绍了如何无异常地检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用try 语句?

How do I check whether a file exists or not, without using the try statement?

推荐答案

如果你检查的原因是你可以做一些类似 if file_exists: open_it() 的事情,使用try 尝试打开它.检查然后打开文件可能会被删除或移动,或者在您检查和尝试打开它之间发生某些事情.

If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

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

If you're not planning to open the file immediately, you can use os.path.isfile

如果路径是现有的常规文件,则返回 True.这遵循符号链接,因此 islink()isfile() 对于相同的路径可能为真.

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

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

如果您需要确定它是一个文件.

if you need to be sure it's a file.

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

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path

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

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

To check a directory, do:

if my_file.is_dir():
    # directory exists

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

To check whether a Path object exists independently of whether is it a file or directory, use exists():

if my_file.exists():
    # path exists

您也可以在 try 块中使用 resolve(strict=True):

You can also use resolve(strict=True) in a try block:

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

这篇关于如何无异常地检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆