linux 下用python 遍历文件夹
我们需要遍历一个文件夹下面的所有 文件名,下面介绍下在python中使用os.walk(路径)可以遍历某路径下的所有文件夹及文件。
具体方法是for <路径名变量>, <文件夹名列表>, <文件名列表> in os.walk(<路径>)。。。
下面我们来看看源代码,很简单:
[root@localhost Python]# vi Traversal.py
#!/usr/bin/python
# write by world77
import os
Directory=raw_input("Please enter directory to traversal:")
###提示输入想遍历的文件夹路径
for root,dirs,files in os.walk(Directory):
print root
for name in dirs:
print "Directory:",name #打印文件夹名
for name in files:
print "FileName:",name #打印文件名
嘿嘿,很简单吧,下面来看看效果:
[root@localhost python]# ls
break.py function_global.py mymodule_demo.py using_list.py
CompressFolder.py function_key.py mymodule.py using_name.py
continue.py function_local.py mymodule.pyc using_name.pyc
DocString.py function_param.py test1.zip using_sys.py
expression.py function_return.py test2.zip using_tuple.py
for.py helloworld.py test3.zip var.py
function1.py if.py test.zip vbar.py
function_default.py mymodule_demo2.py Traversal.py while.py
[root@localhost python]# chmod +x Traversal.py
[root@localhost python]# python Traversal.py
Please enter directory to traversal:/root/python
/root/python
FileName: test2.zip
FileName: using_sys.py
FileName: function_default.py
FileName: function_local.py
FileName: CompressFolder.py
FileName: var.py
FileName: mymodule.py
FileName: vbar.py
FileName: using_tuple.py
FileName: function1.py
FileName: function_global.py
FileName: test.zip
FileName: helloworld.py
FileName: mymodule_demo.py
FileName: test1.zip
FileName: using_list.py
FileName: function_key.py
FileName: continue.py
FileName: using_name.py
FileName: Traversal.py
FileName: break.py
FileName: if.py
FileName: test3.zip
FileName: expression.py
FileName: function_return.py
FileName: DocString.py
FileName: mymodule.pyc
FileName: while.py
FileName: for.py
FileName: mymodule_demo2.py
FileName: function_param.py
FileName: .using_tuple.py.swp
FileName: using_name.pyc
[root@localhost python]#
嘿嘿,很实用,很简单吧,有兴趣还不去试试。。。
相关文章