if语句中and的用法

2024-09-30 00:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检查两种文件的数千个目录。我将索引(idx)限制在四个以内,因为在这个范围内,需要找到两种文件,即“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

这主要是我需要代码来做的。你知道吗


Tags: and文件代码indataifval语句
1条回答
网友
1楼 · 发布于 2024-09-30 00:33:26

我会这样做:

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')]

相关问题 更多 >

    热门问题