python遍历文件夹

来源:互联网 发布:郝斌c语言视频教程mp4 编辑:程序博客网 时间:2024/06/06 03:33

python读取文件夹中所有图像

Load the image files form the folder 3 input: 4imgDir: the direction of the folder 5imgName:the name of the folder 6output: 7data:the data of the dataset 8label:the label of the datset 9'''10def load_Img(imgDir,imgFoldName):11 imgs = os.listdir(imgDir+imgFoldName)12 imgNum = len(imgs)13 data = np.empty((imgNum,1,12,12),dtype="float32")14 label = np.empty((imgNum,),dtype="uint8")15for i in range (imgNum):16 img = Image.open(imgDir+imgFoldName+"/"+imgs[i])17 arr = np.asarray(img,dtype="float32")18 data[i,:,:,:] = arr19 label[i] = int(imgs[i].split('.')[0])20return data,label


1 craterDir = "./data/CraterImg/Adjust/"2 foldName = "East_CraterAdjust12"3 data, label = load_Img(craterDir,foldName)
python 便利文件夹
1 rootdir = 'F:\data'2 list = os.listdir(rootdir) #列出文件夹下所有的目录与文件3 for i in range(0,len(list)):4        path = os.path.join(rootdir,list[i])5        if os.path.isfile(path):6               #你想对文件的操作

python 遍历文件夹两种方法

方法一:os.listdir

复制代码
#!/usr/bin/python# -*- coding: utf-8 -*-import osdef gci(filepath):#遍历filepath下所有文件,包括子目录  files = os.listdir(filepath)  for fi in files:    fi_d = os.path.join(filepath,fi)                if os.path.isdir(fi_d):      gci(fi_d)                      else:      print os.path.join(filepath,fi_d)#递归遍历/root目录下所有文件gci('/root')
复制代码

 方法二:os.walk

#!/usr/bin/python# -*- coding: utf-8 -*-import osfor fpathe,dirs,fs in os.walk('/root'):  for f in fs:    print os.path.join(fpathe,f)

 

列出所有文件:

[i for i in os.listdir('.') if os.path.isdir(i)]

 

列出所有.py文件[i for i in os.listdir('.') if os.path.isfile(i) and os.path.splitext(i)[1]=='.py']

原创粉丝点击