Python遍曆目錄的多種方式

來源:互聯網
上載者:User

標籤:python   遍曆   

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/pythonimport osfrom glob import globdef printSeparator(func):    def deco(path):        print("call method %s, result is:" % func.__name__)        print("-" * 40)        func(path)        print("=" * 40)    return deco@printSeparatordef traverseDirByShell(path):    for f in os.popen(‘ls ‘ + path):        print f.strip()@printSeparatordef traverseDirByGlob(path):    path = os.path.expanduser(path)    for f in glob(path + ‘/*‘):        print f.strip()@printSeparatordef traverseDirByListdir(path):    path = os.path.expanduser(path)    for f in os.listdir(path):        print f.strip()@printSeparatordef 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)

Python遍曆目錄的多種方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.