0

在我当前目录中搜索 HTML 时,如果名称包含任何子字符串,它将假定文件存在并继续操作,而不是说文件不存在。假设我有一个文件“protocolHTTP.html” - 在测试中以确保“protocol.html”引发错误,但它没有。它只是继续程序的运行。

我想确保文件名完全匹配。这是我所拥有的:

for file in glob.glob('*.html'):
        if protocolFile in file:
                with open(file) as f:
                        contents = f.read()
        else:
                print "Could not locate '" + protocolFile + ".html'"
                sys.exit(1)

我可以检查以验证这一点的任何想法或进一步的步骤?

4

2 回答 2

1

我认为您的代码与以下内容相同:

if os.path.isfile(filename):
    with open(filename) as f:
        contents = f.read()
else:
    print 'Could not locate {0}'.format(filename)
    sys.exit(1)
于 2013-09-03T18:50:47.483 回答
1

in不是平等检查,而是集合成员资格检查。看这里并向下滚动到项目符号列表之后的讨论in

>>> 'foo' in 'foobar'
True
>>> 'foo' in 'foo'
True
>>> 'foo' in 'bar'
False

并不是说在搜索一个文件时循环是一个好主意,但是如果您执行了以下操作,它就会起作用。

if '{}.html'.format(protocolFile) == os.path.basename(file):

所以,一般来说,选择 Viktor 的方法。但请确保您也了解其in工作原理。

于 2013-09-03T19:18:37.910 回答