用Python遍历指定目录下的文件,一般有两种常用方法,但它们都是基于Python的os模块。下面两种方法基于Python2.7,主要用到的函数如下: 1.os.listdir(path):列出目录下的所有文件名 2.os.getcwd():获得当前工作目录 3.os.mkdir(dir):创建单个目录 4.os.makedirs('c:\python\a'):创建多级目录 5.os.rmdir(dir):删除单个目录 6.os.removedirs('D:\python'):删除所给路径最后一个目录下所有空目录 7.os.chdir(dir):改变到另一个工作目录上 8.os.path.isfile(path):判断是否是文件 9.os.path.isdir(path):判断是否是目录 10.os.path.join(path,filename):得到文件绝对路径 11.os.chmod(file):修改文件权限与时间戳 12.os.system('dir'):执行操作系统命令 13.os.exec(), os.execvp():启动新进程 14.osspawnv():在后台执行程序 15.os.exit(), os._exit():终止当前进程 16.os.path.split('c:\python\hello.py') --> ('c:\\python', 'hello.py'):分离文件名 17.os.path.splitext('c:\python\hello.py') --> ('c:\\python\\hello', '.py'):分离扩展名 18.os.path.dirname('c:\python\hello.py') --> 'c:\\python':获取路径名 19.os.path.basename('c:\python\hello.py') --> 'hello.py':获取文件名 20.os.path.exists('c:\python\hello.py') --> True:判断文件或目录是否存在 21.os.path.isabs('.\python\') --> False:判断是否是绝对路径 22.os.path.islink('c:\python\hello.py') --> False:判断是否是链接文件 23.os.path.getsize(filename):获取文件大小 24.os.walk():搜索目录下的所有文件 第一种是基于递归函数: #!/usr/bin/python # coding:utf-8 import os def dirList(path): filelist = os.listdir(path) for filename in filelist: filepath = os.path.join(path, filename) if os.path.isdir(filepath): print filepath dirList(filepath) else: print filepath dirList('C:\\Users\\Desktop\\Learning python') 第二种是用os模块下的walk()函数: #!/usr/bin/python # coding:utf-8 Epath=os.walk('C:\\Users\\Desktop\\Learning python') for path,dir,filelist in Epath: for filename in filelist: print os.path.join(path,filename) os.walk()函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件列表。 注:sublime text编辑器下,代码开头加上#coding:utf-8,可以处理代码中出现的中文字符。以上两种方法在遍历中文名文件或文件名时,sublime中使用Ctrl+B会出现: [Decode error - output not utf-8] 错误。但在Python shell或cmd中都可以正常显示中文。 |
|