在if语句中使用'和'

时间:2017-01-13 16:17:56

标签: python python-2.7 if-statement

我需要为两种文件检查数千个目录。我已经将索引或idx限制为少于4,因为在该范围内会有两种需要找到的文件,'jpg'和'.thmb'。但是我需要if语句来要求这两种文件在目录中。 if语句:

if ('.jpg' in val) and ('thmb' in val):

有效,但我不断通过else语句打印输出数据丢失,当它不成立时:

Data missing W:\\North2015\200\10 200001000031.jpg 0
Data missing W:\\North2015\200\10 200001000032.jpg 1
Data missing W:\\North2015\200\100 200014000001.jpg 0
Data missing W:\\North2015\200\100 200014000002.jpg 1
Data missing W:\\North2015\200\101 200014100081.jpg 2

以下是代码:

def missingFileSearch():
    for folder in setFinder():
        for idx,val in enumerate(os.listdir(folder)):
            if idx < 4:
                if ('.jpg' in val) and ('thmb' in val):
                    pass
                else:
                    print'Data missing',folder,val,idx

所以我想知道为什么我通过else语句获取输出。 此外,这行代码被挂断了:

 if val.endswith('.jpg') and ('thmb' in val):
     print'Data is here!',folder,val,idx

这主要是我需要代码做的事情。

1 个答案:

答案 0 :(得分:1)

我会这样做:

def missingFileSearch():
    folders_with_missing = []
    for folder in setFinder():
        thmb_found = False
        jpg_found = False
        for fname in os.listdir(folder):
            thmb_found |= 'thmb' in fname
            jpg_found |= fname.endswith('.jpg')
            if thmb_found and jpg_found:
                break # break inner loop, move on to check next folder
        else: # loop not broken
            if not thmb_found and not jpg_found:
                desc = "no thmb, no .jpg"
            elif not thmb_found:
                desc = "no thmb"
            else:
                desc = "no .jpg"
            folders_with_missing.append((folder, desc))
     return folders_with_missing

我测试了此代码的略微修改版本(没有setFinder()函数):

def missingFileSearch():
    folders_with_missing = []
    for folder in os.listdir(my_dir):
        thmb_found = False
        jpg_found = False
        for fname in os.listdir(os.path.join(my_dir, folder)):
            thmb_found |= 'thmb' in fname
            jpg_found |= fname.endswith('.jpg')
            if thmb_found and jpg_found:
                break # break inner loop, move on to check next folder
        else: # loop not broken
            if not thmb_found and not jpg_found:
                desc = "no thmb, no .jpg"
            elif not thmb_found:
                desc = "no thmb"
            else:
                desc = "no .jpg"
            folders_with_missing.append((folder, desc))
    return folders_with_missing

我创建了四个具有自解释名称的测试文件夹:

>>> os.listdir(my_dir)
['both_thmb_jpg', 'missing_jpg', 'missing_thmb', 'no_files']

然后运行功能:

>>> missingFileSearch()
[('missing_jpg', 'no .jpg'), ('missing_thmb', 'no thmb'), ('no_files', 'no thmb, no .jpg')]