如何通过迭代获取列表中的所有文件?
How do I obtain all the files within list through iteration?
我创建了一个列表,其中包含我想通过目录 C:\ 和 D:\ 获取的特定扩展名。但是我在获取多个文件时遇到问题。如果我只是将 'python.exe' 放入列表并删除 'Hearthstone.exe' 它可以找到并打印并将其附加到 VIP_files 列表。但是一旦我添加 'Hearthstone.exe' 什么都没有发生,甚至没有给出 'python.exe' 路径。这就是我的,我不确定我做错了什么。
import os
from os.path import join
lookfor = ['python.exe','Hearthstone.exe']
VIP_files = []
for root, dirs, files in os.walk('C:\', 'D:\'):
if lookfor in files:
print ("found: %s" % join(root, lookfor))
VIP_files.append(root+ lookfor)
print(VIP_files)
lookfor
是一个列表,files
也是一个列表。你要求 python 在你的 if
中做的是检查列表是否在列表中,例如 [['python.exe','Hearthstone.exe'], ...]
,这当然不存在。
一个快速解决方法是创建 lookfor
一个集合,然后像这样使用集合交集:
import os
from os.path import join
lookfor = {'python.exe','Hearthstone.exe'} # {} set syntax
VIP_files = []
for root, dirs, files in os.walk('C:\', 'D:\'):
found = lookfor.intersection(files)
for f in found:
print("found: {}".format(root + f))
VIP_files.append(root + f)
print(VIP_files)
我创建了一个列表,其中包含我想通过目录 C:\ 和 D:\ 获取的特定扩展名。但是我在获取多个文件时遇到问题。如果我只是将 'python.exe' 放入列表并删除 'Hearthstone.exe' 它可以找到并打印并将其附加到 VIP_files 列表。但是一旦我添加 'Hearthstone.exe' 什么都没有发生,甚至没有给出 'python.exe' 路径。这就是我的,我不确定我做错了什么。
import os
from os.path import join
lookfor = ['python.exe','Hearthstone.exe']
VIP_files = []
for root, dirs, files in os.walk('C:\', 'D:\'):
if lookfor in files:
print ("found: %s" % join(root, lookfor))
VIP_files.append(root+ lookfor)
print(VIP_files)
lookfor
是一个列表,files
也是一个列表。你要求 python 在你的 if
中做的是检查列表是否在列表中,例如 [['python.exe','Hearthstone.exe'], ...]
,这当然不存在。
一个快速解决方法是创建 lookfor
一个集合,然后像这样使用集合交集:
import os
from os.path import join
lookfor = {'python.exe','Hearthstone.exe'} # {} set syntax
VIP_files = []
for root, dirs, files in os.walk('C:\', 'D:\'):
found = lookfor.intersection(files)
for f in found:
print("found: {}".format(root + f))
VIP_files.append(root + f)
print(VIP_files)