os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir("dirname") 改變當前腳本工作目錄;相當于shell下cd
os.curdir 返回當前目錄: ('.')
os.pardir 獲取當前目錄的父目錄字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄
os.removedirs('dirname1') 若目錄為空,則刪除,并遞歸到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir('dirname') 生成單級目錄;相當于shell中mkdir dirname
os.rmdir('dirname') 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當于shell中rmdir dirname
os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印
os.remove() 刪除一個文件
os.rename("oldname","newname") 重命名文件/目錄
os.stat('path/filename') 獲取文件/目錄信息
os.symlink('path/filename','ln_filename') 創建符號鏈接,源需絕對路徑
os.utime() 修改時間屬性>>> import os>>> stinfo = os.stat('c.py')>>> print "access time of c.py: %s /nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)access time of c.py: 1375448908.0modified time of c.py: 1369735909.0>>> os.utime('c.py',(1375448978,1369735977))>>> print "access time of c.py: %s /nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)access time of c.py: 1375448908.0modified time of c.py: 1369735909.0退出Python交互模式,再次進入>>> import os>>> stinfo = os.stat('c.py')>>> print "access time of c.py: %s /nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)access time of c.py: 1375448978.0modified time of c.py: 1369735977.0
os.walk() 生成一個目錄樹下的所有文件名
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
top表示需要遍歷的目錄樹的路徑 topdown的默認值是”True”,表示首先返回目錄樹下的文件,然后在遍歷目錄樹的子目錄.Topdown的值為”False”時,則表示先遍歷目錄樹的子目錄,返回子目錄下的文件,最后返回根目錄下的文件 onerror的默認值是”None”,表示忽略文件遍歷時產生的錯誤.如果不為空,則提供一個自定義函數提示錯誤信息后繼續遍歷或拋出異常中止遍歷該函數返回一個元組,該元組有3個元素,這3個元素分別表示每次遍歷的路徑名,目錄列表和文件列表
新聞熱點
疑難解答