Python一般有两种遍历文件夹或文件的操作方法。一种是使用其封装的walk方法进行二级操作:importosforroot,dirs,filesinos.walk("/Users/cxhuan/Downloads/globtest/hello"):fordirindirs:print(os.path.join(root,dir))forfileinfiles:print(os.path.join(root,file))以上代码运行结果如下:/Users/cxhuan/Downloads/globtest/hello/world/Users/cxhuan/Downloads/globtest/hello/.DS_Store/Users/cxhuan/Downloads/globtest/hello/hello3.txt/Users/cxhuan/Downloads/globtest/hello/hello2.txt/Users/cxhuan/Downloads/globtest/你好/hello1.txt/Users/cxhuan/Downloads/globtest/hello/world/world1.txt/Users/cxhuan/Downloads/globtest/hello/world/world3.txt/Users/cxhuan/Downloads/globtest/hello/world/world2.txt上面程序使用foreach循环输出os.walk读取的所有路径root、目录名dirs和文件名文件,即三个文件数组。join方法是将其路径与目录名或文件名连接起来,组成一个完整的目录。另一种是利用递归思维,写成如下形式:f=os.path.join(pathname,f)ifos.path.isdir(f):dirAll(f)else:dirname=os.path.dirname(f)baseName=os.path.basename(f)ifdirname.endswith(os.sep):files.append(dirname+baseName)else:files.append(dirname+os.sep+baseName)dirAll("/Users/cxhuan/Downloads/globtest/hello")forfinfiles:打印(f)运行上面的代码,得到与上面相同的结果。这两种方法都可以,但是写起来比较麻烦,尤其是第二种方法,一不小心可能会出bug。今天我们来介绍第三种方法——使用glob模块遍历文件。简介glob是python自带的一个文件操作模块,以简单实用着称。因为这个模块的功能比较简单,所以上手和使用起来也非常容易。主要用于查找符合一定规则的文件路径。使用该模块查找文件,只需要使用*、?这三个匹配字符即可。and[]:*:匹配0个或多个字符;?:匹配单个字符;[]:匹配指定范围内的字符,如:[0-9]匹配数字。glob.glob方法glob.glob方法基本上返回所有匹配文件路径的列表。它只有一个参数pathname,定义文件路径匹配规则,可以是绝对路径也可以是相对路径。使用*来匹配我们可以使用*来匹配零个或多个字符。输出目录下的子目录或文件:forp1inglob.glob('/Users/cxhuan/Downloads/globtest/*'):print(p1)运行以上代码,会输出globtest文件夹下的唯一目录,输出如下:/Users/cxhuan/Downloads/globtest/hello我们也可以通过指定级别来遍历文件或文件夹:forpinglob.glob('/Users/cxhuan/Downloads/globtest/*/*'):print(p)上面的代码会遍历globtest文件夹和子文件夹,打印出所有文件或文件夹路径:/Users/cxhuan/Downloads/globtest/hello/world/Users/cxhuan/Downloads/globtest/hello/hello3.txt/Users/cxhuan/Downloads/globtest/hello/hello2.txt/Users/cxhuan/Downloads/globtest/hello/hello1.txt我们还可以过滤文件或文件夹:forpinglob.glob('/Users/cxhuan/Downloads/globtest/hello/*3.txt'):print(p)上述代码的值匹配hello目录下文件名以'3'结尾的txt文件,运行结果如下:/Users/cxhuan/下载/globtest/你好/hello3.txt使用?匹配我们可以使用问号(?)来匹配任何单个字符。forpinglob.glob('/Users/cxhuan/Downloads/globtest/hello/hello?.txt'):print(p)以上代码输出hello目录下以'hello'开头的txt文件,输出结果如下:/Users/cxhuan/Downloads/globtest/hello/hello3.txt/Users/cxhuan/Downloads/globtest/hello/hello2.txt/Users/cxhuan/Downloads/globtest/hello/hello1.txtUsing[]为了匹配我们可以使用[]来匹配一个范围:forpinglob.glob('/Users/cxhuan/Downloads/globtest/hello/*[0-2].*'):print(p)我们想要得到hello目录下的文件文件名以0到2之间的数字结尾的文件,运行上面的代码,得到的输出是:/Users/cxhuan/Downloads/globtest/hello/hello2.txt/Users/cxhuan/Downloads/globtest/hello/hello1.txtglob。iglob方法Python的glob方法可以遍历一个文件夹下的所有文件,返回一个list列表。而iglob方法一次只获取一个匹配路径。下面用一个简单的例子来说明两者的区别:p=glob.glob('/Users/cxhuan/Downloads/globtest/hello/hello?.*')print(p)print('--------------------')p=glob.iglob('/Users/cxhuan/Downloads/globtest/hello/hello?.*')print(p)运行上面的代码,返回的结果是:['/Users/cxhuan/Downloads/globtest/hello/hello3.txt','/Users/cxhuan/Downloads/globtest/hello/hello2.txt','/Users/cxhuan/Downloads/globtest/hello/hello1.txt']--------------------
