使用布尔值检查目录中是否存在多个 csv 文件,但它不起作用

Check if the multiple csv files exist in the directory by using boolean but its not working

我已经创建了一个定义来检查目录中的多个文件。 objective 是在进一步的程序中执行这个定义。但它不起作用,即使文件存在于目录中。请提出建议。

import os
def is_file_exist():
    return (bool(os.path.exists(dir + 'file1.csv')),
            bool(os.path.exists(dir + 'file2.csv')),
            bool(os.path.exists(dir + 'file3.csv')))

if is_file_exist() == True:
    print('Do Something')

如评论所述,您返回的是元组而不是布尔值。要检查可迭代对象中的所有值是否为真,可以使用 all() 方法。

import os
def is_file_exist():
    return all((bool(os.path.exists(dir + 'file1.csv')),
            bool(os.path.exists(dir + 'file2.csv')),
            bool(os.path.exists(dir + 'file3.csv'))))

if is_file_exist() == True:
    print('Do Something')

所以你正在做的是返回一个元组,它可以有 True 作为元素或 'False' 作为元素或两者都有。

所以在所有情况下,元组都是non-empty,因此是真值。

因此条件将永远为真。