歡迎您光臨本站 註冊首頁

linux 下用python 遍歷文件夾

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
我們需要遍歷一個文件夾下面的所有 文件名,下面介紹下在Python中使用os.walk(路徑)可以遍歷某路徑下的所有文件夾及文件.
具體方法是for <路徑名變數>, <文件夾名列表>, <文件名列表> in os.walk(<路徑>)... 下面我們來看看源代碼,很簡單:
[[email protected] 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 #列印文件名

嘿嘿,很簡單吧,下面來看看效果:[[email protected] python]# lsbreak.py function_global.py mymodule_demo.py using_list.pyCompressFolder.py function_key.py mymodule.py using_name.pycontinue.py function_local.py mymodule.pyc using_name.pycDocString.py function_param.py test1.zip using_sys.pyexpression.py function_return.py test2.zip using_tuple.pyfor.py helloworld.py test3.zip var.pyfunction1.py if.py test.zip vbar.pyfunction_default.py mymodule_demo2.py Traversal.py while.py[[email protected] python]# chmod x Traversal.py [[email protected] python]# python Traversal.py Please enter directory to traversal:/root/python/root/pythonFileName: test2.zipFileName: using_sys.pyFileName: function_default.pyFileName: function_local.pyFileName: CompressFolder.pyFileName: var.pyFileName: mymodule.pyFileName: vbar.pyFileName: using_tuple.pyFileName: function1.pyFileName: function_global.pyFileName: test.zipFileName: helloworld.pyFileName: mymodule_demo.pyFileName: test1.zipFileName: using_list.pyFileName: function_key.pyFileName: continue.pyFileName: using_name.pyFileName: Traversal.pyFileName: break.pyFileName: if.pyFileName: test3.zipFileName: expression.pyFileName: function_return.pyFileName: DocString.pyFileName: mymodule.pycFileName: while.pyFileName: for.pyFileName: mymodule_demo2.pyFileName: function_param.pyFileName: .using_tuple.py.swpFileName: using_name.pyc[[email protected] python]#



嘿嘿,很實用,很簡單吧,有興趣還不去試試...

本文出自 「你是路人甲還是霍元甲」 博客,請務必保留此出處http://world77.blog.51cto.com/414605/467598


[火星人 ] linux 下用python 遍歷文件夾已經有580次圍觀

http://coctec.com/docs/linux/show-post-49921.html