### 目錄遍歷
### 包:
os ?os.path
### 函數:
os.listdir(dirname):列出dirname下的目錄和文件
os.getcwd():獲得當前工作目錄
os.curdir:返回當前目錄('.')
os.chdir(dirname):改變工作目錄到dirname
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個文件,不存在name也返回false
os.path.exists(name):判斷是否存在文件或目錄name
os.path.getsize(name):獲得文件大小,如果name是目錄返回0
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規范path字符串形式
os.path.split(name):分割文件名與目錄(事實上,如果你完全使用目錄,它也會將最后一個目錄作為文件名而分離,同時它不會判斷文件或目錄是否存在)
os.path.splitext():分離文件名與擴展名
os.path.join(path,name):連接目錄與文件名或目錄
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路徑
### 遞歸法
~~~
#coding:utf8
import os
def dirList(path,allfile):
filelist=os.listdir(path)
for filename in filelist:
filepath=os.path.join(path,filename)
if os.path.isdir(filepath):
dirList(filepath,allfile)
allfile.append(filepath)
allfile=[]
dirList('D:\\pythonPro\\test',allfile)
print allfile
~~~
### os.walk()法
os.walk(path)返回一個生成器,可以用next()方法,或者for循環訪問該生成器的每一個元素。他的每個部分都是一個三元組,('目錄x',[目錄x下的目錄list],[目錄x下面的文件list])
~~~
path='D:\\pythonPro\\test'
allfile1=[]
g=os.walk(path)
for root,dirs,files in os.walk(path):
for filename in files:
allfile1.append(os.path.join(root,filename))
for dirname in dirs:
allfile1.append(os.path.join(root,dirname))
print allfile1
~~~
os.walk()方法操作更加方便,實用。