如何检查是否存在文件,而不使用试用声明?


当前回答

另一个可能的选项是检查文件名是否在目录中使用 os.listdir():

import os
if 'foo.txt' in os.listdir():
    # Do things

如果是真相,如果是虚假,如果不是真相。

其他回答

import os

if os.path.isfile(filepath):
   print("File exists")

使用 os.path.isfile(), os.path.isdir() 和 os.path.exists() 的文件和文件夹进行测试

假设“路径”是有效的路径,此表显示了每个函数为文件和文件夹返回的内容:

此分類上一篇

您还可以测试文件是否是一种特定类型的文件,使用 os.path.splitext() 获取扩展(如果您还不知道)

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True

查看文件或目录存在

你可以遵循这三种方式:

使用 isfile( )

注意1: os.path.isfile 仅用于文件

import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists

二、使用存在

注意2: os.path.exists 用于文件和目录

import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) # True if directory exists

pathlib.Path 方法(包含在 Python 3+ 中,可与 Python 2 的 pip 安装)

from pathlib import Path
Path(filename).exists()

此外, os.access():

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()

是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。

Python 3.4+ 有一个以对象为导向的路径模块: pathlib. 使用这个新模块,您可以检查是否存在这样的文件:

import pathlib
p = pathlib.Path('path/to/file')
if p.is_file():  # or p.is_dir() to see if it is a directory
    # do stuff

在打开文件时,您仍然可以(通常应该)使用尝试/排除区块:

try:
    with p.open() as f:
        # do awesome stuff
except OSError:
    print('Well darn.')

pathlib 模块有很多很好的东西在它:方便的旋转,检查文件的所有者,更容易的路径加入,等等,值得检查。 如果你在更老的 Python (版本 2.6 或更晚),你仍然可以安装 pathlib 带 pip:

# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2

然后将其输入如下:

# Older Python versions
import pathlib2 as pathlib