python遍历目录_Python遍历目录的4种方法
1.os.popen運行shell列表命令
def traverseDirByShell(path):
for f in os.popen('ls ' + path):
print f.strip()
2.利用glob模塊
glob.glob(path)返回帶目錄的文件名.通配符和shell相似.path不能包含shell變量.
def traverseDirByGlob(path):
path = os.path.expanduser(path)
for f in glob(path + '/*'):
print f.strip()
3.利用os.listdir(推薦)
該方法返回不帶根目錄的文件名或子目錄名
def traverseDirByListdir(path):
path = os.path.expanduser(path)
for f in os.listdir(path):
print f.strip()
4.利用os.walk(推薦)
返回一個包含3個項目的元組:當前目錄名稱,子目錄名稱,子文件名稱
def traverseDirByOSWalk(path):
path = os.path.expanduser(path)
for (dirname, subdir, subfile) in os.walk(path):
#print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
print('[' + dirname + ']')
for f in subfile:
print(os.path.join(dirname, f))
整合代碼:
#!/usr/bin/python
import os
from glob import glob
def printSeparator(func):
def deco(path):
print("call method %s, result is:" % func.__name__)
print("-" * 40)
func(path)
print("=" * 40)
return deco
@printSeparator
def traverseDirByShell(path):
for f in os.popen('ls ' + path):
print f.strip()
@printSeparator
def traverseDirByGlob(path):
path = os.path.expanduser(path)
for f in glob(path + '/*'):
print f.strip()
@printSeparator
def traverseDirByListdir(path):
path = os.path.expanduser(path)
for f in os.listdir(path):
print f.strip()
@printSeparator
def traverseDirByOSWalk(path):
path = os.path.expanduser(path)
for (dirname, subdir, subfile) in os.walk(path):
#print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
print('[' + dirname + ']')
for f in subfile:
print(os.path.join(dirname, f))
if __name__ == '__main__':
path = r'~/src/py'
traverseDirByGlob(path)
traverseDirByGlob(path)
traverseDirByListdir(path)
traverseDirByOSWalk(path)
代碼節選自codego.net
來自 “ ITPUB博客 ” ,鏈接:http://blog.itpub.net/30193029/viewspace-1571247/,如需轉載,請注明出處,否則將追究法律責任。
總結
以上是生活随笔為你收集整理的python遍历目录_Python遍历目录的4种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Jenkins 流水线 获取git 分支
- 下一篇: 用python写一个简单的爬虫_用Pyt