1. 基本实现 [root@localhost ~]# cat dirfile.py 1. import os 2. path= '/tmp' 3. for dirpath,dirnames,filenames in os.walk(path): 4. for file in filenames: 5. fullpath=os.path.join(dirpath,file) 6. print fullpath 执行结果如下: 1. [root @localhost ~]# python dirfile.py 2. /tmp/yum.log 3. /tmp/pulse-3QSA3BbwpQ49/pid 4. /tmp/pulse-3QSA3BbwpQ49/ native 5. /tmp/.esd- 0 /socket 2. 在上例的基础上传递参数 1. import os,sys 2. path=sys.argv[ 1 ] 3. for dirpath,dirnames,filenames in os.walk(path): 4. for file in filenames: 5. fullpath=os.path.join(dirpath,file) 6. print fullpath 执行方式为:[root@localhost ~]# python dirfile.py /tmp 在这里,sys.argv[1]是接受参数,也可以定义sys.argv[2]接受第二个参数 3. 如何用函数实现 01. import os,sys 02. path= '/tmp' 03. def paths(path): 04. path_collection=[] 05. for dirpath,dirnames,filenames in os.walk(path): 06. for file in filenames: 07. fullpath=os.path.join(dirpath,file) 08. path_collection.append(fullpath) 09. return path_collection 10. for file in paths(path): 11. print file 4. 如何封装成类 01. import os,sys 02. class diskwalk(object): 03. def __init__(self,path): 04. self.path = path 05. def paths(self): 06. path=self.path 07. path_collection=[] 08. for dirpath,dirnames,filenames in os.walk(path): 09. for file in filenames: 10. fullpath=os.path.join(dirpath,file) 11. path_collection.append(fullpath) 12. return path_collection 13. if __name__ == '__main__' : 14. for file in diskwalk(sys.argv[ 1 ]).paths(): 15. print file PS: 1> def __init__():函数,也叫初始化函数。 self.path = path可以理解为初始化定义了1个变量。 在后面的def里面调用的时候必须要使用self.path而不能使用path 2> __name__ == '__main__' 模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这种情况下, __name__ 的值将是一个特别缺省"__main__"。上述类中加上__name__ == '__main__'的判断语句,可以直接在终端环境下执行python dirfile.py /tmp进行测试,不必非得在交互式环境下导入模块进行测试。 具体可参考:http://www.cnblogs.com/xuxm2007/archive/2010/08/04/1792463.html 3> 关于参数self,可参考 http://blog.csdn.net/taohuaxinmu123/article/details/38558377 |
|