Python 检查给定目录中是否存在来自多个文件列表的文件

Python 检查给定目录中是否存在来自多个文件列表的文件,python,Python,我需要检查多个文件列表并确定存在哪些文件。虽然我认为可以做得更好,但我已经尝试了以下方法。我在下面编写了一些伪代码: a_files = ["A", "B", "c"] A_files = ["abc", "def", "fgh"] a_file_found = None A_file_found = None for a_ in a_files: if os.path.isfile(a_): a_file_found = "B" for A_ in A_files: if

我需要检查多个文件列表并确定存在哪些文件。虽然我认为可以做得更好,但我已经尝试了以下方法。我在下面编写了一些伪代码:

a_files = ["A", "B", "c"]
A_files = ["abc", "def", "fgh"]
a_file_found = None
A_file_found = None
for a_ in a_files:
  if os.path.isfile(a_):
      a_file_found = "B"
for A_ in A_files:
   if os.path.isfile(A_):
      A_file_found = a_

定义函数以避免重复循环:

def files_exist(file_list):
    file_found = None
    for item in file_list:
        if os.path.isfile(item):
            file_found = item
    return file_found

然后你可以将你想要的所有列表传递给这个函数。

你知道你可以通过使用
+
符号在python中合并两个
list

> a = [1, 2]
> b = [3, 4]
> c = a + b
> print(c)
[1, 2, 3, 4]
您可以合并现有的两个列表,检查每个文件是否存在,然后返回现有文件的列表。让我们在函数定义中定义它

import os.path

def get_existing_files(list_1, list_2):
    merged_list = list_1 + list_2
    result = []
    for _file in merged_list:
        if os.path.exists(_file):
            result.append(_file)
    return result
或者如果您只想在找到列表中的第一个文件时返回一个
布尔值

import os.path

def any_file_exists(list_1, list_2):
    merged_list = list_1 + list_2
    result = []
    for _file in merged_list:
        if os.path.exists(_file):
            return True
    return False

要确定列表中存在哪些文件,您需要从空白列表开始,而不是
None

>>> import os.path
>>> def validateFiles(fileList):
...    filesPresent = []
...    for eachFile in fileList:
...        if os.path.isfile(eachFile):
...            filesPresent.append(eachFile)
...    return filesPresent
>>> a_files = ["A", "B", "c"]
>>> validateFiles(a_files)
['A', 'B']     #: Sample output

你能用输入和输出的例子清楚地解释你的情况吗?将比一些毫无意义的伪代码更容易。
file\u found=item
将只返回从列表中找到的最后一个文件,并覆盖以前找到的所有文件。不妨做
返回项
@smci覆盖是他在原始代码中所做的,这就是我这样写的原因。是的,但他的伪代码不符合规范“确定存在哪些文件”。。。列表/列表理解/听写会更好。
>>> import os.path
>>> def validateFiles(fileList):
...    filesPresent = []
...    for eachFile in fileList:
...        if os.path.isfile(eachFile):
...            filesPresent.append(eachFile)
...    return filesPresent
>>> a_files = ["A", "B", "c"]
>>> validateFiles(a_files)
['A', 'B']     #: Sample output
>>> import glob
>>> a=['A','b', 'j_help.py', 'pre-push']
>>> [glob.glob(_file) for _file in a]
[[], [], ['j_help.py']]
>>> a=['A','b', 'j_help.py', 'pre-push']
>>> sum([glob.glob(_file) for _file in a], [])
['j_help.py', 'pre-push']