Làm cách nào để giới hạn os.walk
chỉ trả lại các tệp trong thư mục mà tôi cung cấp?
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
files_with_full_path = [f.path for f in os.scandir(dir) if f.is_file()]
. Trong trường hợp bạn chỉ cần sử dụng tên tệp f.name
thay vì f.path
. Đây là giải pháp nhanh nhất và nhanh hơn nhiều so với bất kỳ giải pháp nào walk
hoặc listdir
xem stackoverflow.com/a/40347279/2441026 .