How to check whether a file exists?

如何查看文件是否存在,而不使用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.

If you're not planning to open the file immediately, you can use os.path.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.

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

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

if my_file.exists():
    # path exists

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

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

You have the os.path.exists function:

import os.path
os.path.exists(file_path)

This returns True for both files and directories but you can instead use

os.path.isfile(file_name)

to test if it's a file specifically. It follows symlinks.


Unlike isfile() , exists() will return True for directories.
So depending on if you want only plain files or also directories, you'll use isfile() or exists() . Here is a simple REPL output.

>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
链接地址: http://www.djcxy.com/p/102.html

上一篇: 如何在另一个JavaScript文件中包含JavaScript文件?

下一篇: 如何检查文件是否存在?