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


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