python 學習筆記 os模塊常用項

刪除指定目錄樹中的空目錄

#!/usr/bin env python

import os
import sys

dir =sys.argv[1]
if os.path.isdir(dir):
   for root,dirs,files in os.walk(dir,topdown=False):#從最裏向外遍歷
      for d in dirs:
         if not os.listdir(os.path.join(root,d)):#判斷目錄是否爲空
            os.rmdir(os.path.join(root,d))
else:
   print '%s is not dir' %dir

os.walk()函數的用法

   for root,dirs,files in os.walk(path,topdown=True,onerro=None)

   返回一個三元元組,root爲每次遍歷的路徑,dirs 返回一個目錄列表,files 返回一個文件列表

   topdown 默認(True)從外往裏,False 爲從裏往外

os 模塊常用項

os.listdir(path)

os.getcwd()

os.chdir(path)

os.rmdir(path)

os.remove()

os.path.split(path)

os.path.join(path,filename)

os.path.isdir()

os.path.isfile()

os.path.exists()

os.path.getsize()

os.path.basename()

os.path.dirname()

os.sep


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章