我需要检查多个文件列表并确定存在哪些文件。我已经尝试过以下方式,但我认为可以做得更好。我在下面写了一些伪代码:
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_
答案 0 :(得分:3)
import os.path
# files "a" and "b" exist, "c" does not exist
a_files = ["a", "b", "c"];
a_exist = [f for f in a_files if os.path.isfile(f)];
a_non_exist = list(set(a_exist) ^ set(a_files))
print("existing: %s" % a_exist) # ['a', 'b']
print("non existing: %s" % a_non_exist) # ['c']
答案 1 :(得分:0)
定义函数以避免重复循环:
def files_exist(file_list):
file_found = None
for item in file_list:
if os.path.isfile(item):
file_found = item
return file_found
然后你可以将你想要的所有列表传递给这个函数。
答案 2 :(得分:0)
您知道只需使用list
符号即可在python中合并两个+
吗?
> 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
或者,如果您只想找到列表中的第一个文件,则只返回boolean
。
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
答案 3 :(得分:0)
要确定列表中存在哪些文件,您需要以空白列表而不是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
答案 4 :(得分:0)
>>> 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']