os.listdir(path)中有一个参数,就是传入相应的路径,将会返回那个目录下的所有文件名。
这个函数在遍历文件操作时很常用。
比如:
def load_data(file_path):
""" file_path: ./datasets/
datasets/
train/
Classification_1/
img_1.jpg
img_2.jpg
img_3.jpg
...
Classification_2/
img_1.jpg
img_2.jpg
img_3.jpg
...
Classification_3/
...
val/
Classification_1/
...
Classification_2/
...
test/
... """
class_train_filename = os.listdir(file_path + 'train' + '/')
class_val_filename = os.listdir(file_path + 'val' + '/')
class_test_filename = os.listdir(file_path + 'test' + '/')
train_data, val_data, test_data = [], [], []
train_label, val_label, test_label = [], [], []
for index in range(len(class_train_filename)):
path = file_path + 'train' + '/' + class_train_filename[index]
dir_name_list = os.listdir(path + '/')
train_data.append(dir_name_list)
train_label.append(class_train_filename[index])
for index in range(len(class_val_filename)):
path = file_path + 'val' + '/' + class_val_filename[index]
dir_name_list = os.listdir(path + '/')
train_data.append(dir_name_list)
train_label.append(class_val_filename[index])
for index in range(len(class_test_filename)):
path = file_path + 'test' + '/' + class_test_filename[index]
dir_name_list = os.listdir(path + '/')
train_data.append(dir_name_list)
train_label.append(class_test_filename[index])
return train_data, train_label, \
val_data, val_label, \
test_data, test_label