写了个示例代码给你
import os
path = "CBIS-DDSM" # 根目录
mass_test_list = []
mass_train_list = []
calc_test_list = []
calc_train_list = []
for root, dirs, files in os.walk(path):
for dir in dirs:
if dir.startswith("Mass-Test_"):
sub_path = os.path.join(root, dir)
for sub_root, sub_dirs, sub_files in os.walk(sub_path):
for sub_file in sub_files:
if sub_file.endswith(".dcm"):
mass_test_list.append(os.path.join(sub_root, sub_file))
elif dir.startswith("Mass-Training_"):
sub_path = os.path.join(root, dir)
for sub_root, sub_dirs, sub_files in os.walk(sub_path):
for sub_file in sub_files:
if sub_file.endswith(".dcm"):
mass_train_list.append(os.path.join(sub_root, sub_file))
elif dir.startswith("Calc-Test_"):
sub_path = os.path.join(root, dir)
for sub_root, sub_dirs, sub_files in os.walk(sub_path):
for sub_file in sub_files:
if sub_file.endswith(".dcm"):
calc_test_list.append(os.path.join(sub_root, sub_file))
elif dir.startswith("Calc-Training_"):
sub_path = os.path.join(root, dir)
for sub_root, sub_dirs, sub_files in os.walk(sub_path):
for sub_file in sub_files:
if sub_file.endswith(".dcm"):
calc_train_list.append(os.path.join(sub_root, sub_file))