200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python循环遍历文件夹_如何用Python实现目录遍历

python循环遍历文件夹_如何用Python实现目录遍历

时间:2021-05-16 16:15:19

相关推荐

python循环遍历文件夹_如何用Python实现目录遍历

1. 基本实现

[root@localhost ~]# cat dirfile.py

importos

path='/tmp'

for dirpath,dirnames,filenames inos.walk(path):for file infilenames:

fullpath=os.path.join(dirpath,file)print fullpath

执行结果如下:

[root@localhost ~]# python dirfile.py/tmp/yum.log/tmp/pulse-3QSA3BbwpQ49/pid/tmp/pulse-3QSA3BbwpQ49/native/tmp/.esd-0/socket

2. 在上例的基础上传递参数

importos,sys

path=sys.argv[1]for dirpath,dirnames,filenames inos.walk(path):for file infilenames:

fullpath=os.path.join(dirpath,file)print fullpath

执行方式为:[root@localhost ~]# python dirfile.py /tmp

在这里,sys.argv[1]是接受参数,也可以定义sys.argv[2]接受第二个参数

3. 如何用函数实现

importos,sys

path='/tmp'

defpaths(path):

path_collection=[]for dirpath,dirnames,filenames inos.walk(path):for file infilenames:

fullpath=os.path.join(dirpath,file)

path_collection.append(fullpath)returnpath_collectionfor file inpaths(path):print file

4. 如何封装成类

importos,sysclassdiskwalk(object):def __init__(self,path):

self.path=pathdefpaths(self):

path=self.path

path_collection=[]for dirpath,dirnames,filenames inos.walk(path):for file infilenames:

fullpath=os.path.join(dirpath,file)

path_collection.append(fullpath)returnpath_collectionif __name__ == '__main__':for file in diskwalk(sys.argv[1]).paths():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进行测试,不必非得在交互式环境下导入模块进行测试。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。