本文主要是介绍os.listdir()详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
os.listdir(path)中有一个参数,就是传入相应的路径,将会返回那个目录下的所有文件名。
这个函数在遍历文件操作时很常用。
比如:
def load_data(file_path):""" file_path: ./datasets/datasets/train/Classification_1/img_1.jpgimg_2.jpgimg_3.jpg...Classification_2/img_1.jpgimg_2.jpgimg_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
这篇关于os.listdir()详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!