Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

python - 如何检查文件是否存在无例外?(How do I check whether a file exists without exceptions?)

不使用try语句如何查看文件是否存在?

  ask by spence91 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(如果您要检查的原因是可以执行诸如if file_exists: open_it() ,则try尝试打开它更安全。)

Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

(检查然后打开可能会导致文件被删除或移动,或者介于检查和尝试打开文件之间。)

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

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

Return True if path is an existing regular file.

(如果path是现有的常规文件,则返回True 。)

This follows symbolic links, so both islink() and isfile() can be true for the same path.

(这遵循符号链接,因此,对于同一路径, islink()isfile()都可以为true。)

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

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

(如果您需要确保它是一个文件。)

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

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

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

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

(要检查Path对象是否独立于文件或目录而exists() ,请使用exists() :)

if my_file.exists():
    # path exists

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...