Python實現對檔案夾內文字檔遞迴尋找

來源:互聯網
上載者:User

標籤:pen   ble   .cpp   std   sts   ror   odi   open   com   

經常有這樣的需求:在一個文字檔裡尋找特定字串,這很好實現,用任何文本查看工具幾乎都可以做到。而有的時候,想尋找一個檔案夾下的所有文字檔(特定尾碼),我就遇到了這樣的問題:想找到Blender的原始碼中關於SPH的實現代碼。於是寫了下面的簡單程式:

#!/usr/bin/env python3import osdef Search(rootDir, suffixes, arg):       for lists in os.listdir(rootDir):               path = os.path.join(rootDir, lists)        if os.path.isfile(path):            if path.endswith(suffixes):                try:                    with open(path, encoding=‘utf_8‘) as fh:                        lineNum = 0                        for line in fh:                            lineNum += 1                            if arg in line:                                print(lineNum, ‘:‘, path, ‘\n‘, line)                        fh.close()                except:                    print(‘error: ‘, path, ‘\n‘)        if os.path.isdir(path):            Search(path, suffixes, arg)Search(r‘D:\blender-2.70‘, (‘.c‘,‘.cpp‘,‘.h‘,‘.hpp‘), ‘SPH ‘)

程式雖小,但很實用,運行結果如下:

 

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.