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


当前回答

使用 os.path.isfile() 与 os.access():

import os

PATH = './file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print("File exists and is readable")
else:
    print("Either the file is missing or not readable")

其他回答

它被认为是更好的风格,避免赛车条件。

不要用我的话来支持这个理论,这里有几个:

风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件

你可以写布莱恩的建议,没有尝试:

from contextlib import suppress

with suppress(IOError), open('filename'):
    process()

suppress 是 Python 3.4 的组成部分。在旧版本中,您可以快速写下自己的 suppress:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。

python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"

如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。

import numpy as np
np.DataSource().exists("path/to/your/file")

这将根据它的存在返回真实或虚假。

您可以使用Python的“OS”图书馆:

>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") 
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False