一 常用函數
os模塊
os.sep 表示默認的文件路徑分隔符,windows為\, linux為/
os.walk(spath): 用來遍歷目錄下的文件和子目錄
os.listdir(dirname):列出dirname下的目錄和文件
os.mkdir() : 創建目錄
os.makedirs(): 創建目錄,包含中間級目錄
os.remove():刪除文件,不能是目錄
os.rmdir():刪除空目錄
os.removedirs(path):刪除目錄及其子目錄
os.rename(src, dst) :修改文件名
os.renames(old, new) :修改文件或目錄名,包含中間級
os.chdir("/tmp") : 更改當前目錄
os.chmod( "c:\\test\\buildid.txt", stat.S_IWRITE ) : 去除文件的只讀屬性
os.path模塊
os.path.pathsep 表示默認的路徑間的分隔符,windows為; Linux為:
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個文件,不存在name也返回false
os.path.exists(name):判斷是否存在文件或目錄name
os.path.getsize(name):獲得文件大小,如果name是目錄返回0L
os.path.getctime(name):獲得文件的創建時間
os.path.getmtime(name):獲得文件的修改時間
os.path.getatime(name):獲得文件的最后訪問時間
?
os.path.isabs(name):測試是否是絕對路徑
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規范path字符串形式
os.path.relpath(path, start='.'):返回路徑的相對版本
os.path.split(name):分割文件名與目錄(事實上,如果你完全使用目錄,它也會將最后一個目錄作為文件名而分離,同時它不會判斷文件或目錄是否存在)
os.path.splitext():分離文件名與擴展名
os.path.splitdrive():分離驅動名或unc名字
os.path.join(path,name):連接目錄與文件名或目錄
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路徑
shutil模塊
shutil.copyfile(src, dst): 拷貝文件
shutil.copytree(srcDir, dstDir) : 拷貝目錄
?
shutil.rmtree('dir') : 刪除非空文件夾
shutil.move('old','new') :修改文件和目錄名稱
?
glob模塊
匹配文件:glob.glob(r”c:\linuxany\*.py”)
?
二 實例 (os.walk的遍歷過程如下)
import?os
#?tree?c:\test?/f
#C:\TEST
#│??test.log
#│
#├─test2
#│??????test2.log
#│
#└─test3
tree?=?os.walk('C:/test')
for?directoryItem?in?tree:
????directory=directoryItem[0]
????subDirectories=directoryItem[1]
????filesInDirectory=directoryItem[2]????
????print('-----------------')
????print('the?directory?is?:',?directory)
????print('the?sub?directories?are?:?',?subDirectories)
????print('the?files?are?:',?filesInDirectory)
#-----------------
#the?directory?is?:?C:/test
#the?sub?directories?are?:??['test2',?'test3']
#the?files?are?:?['test.log']
#-----------------
#the?directory?is?:?C:/test\test2
#the?sub?directories?are?:??[]
#the?files?are?:?['test2.log']
#-----------------
#the?directory?is?:?C:/test\test3
#the?sub?directories?are?:??[]
#the?files?are?:?[]
完!
?