簡體   English   中英

在Python中運行多個查找和替換(在文件夾和子文件夾中的每個文件上)

[英]Run multiple find and replaces in Python (on every file in the folder and sub-folder)

我有一個文件夾(課程),包含子文件夾和隨機數量的文件。 我想運行多個搜索並替換這些隨機文件。 是否可以對.html進行通配符搜索並在每個html文件上運行替換?

搜索和替換:

  • 1) "</b>""</strong>"
  • 2) "</a>""</h>"
  • 3) "<p>""</p>"
  • 此外,所有這些替換都必須在文件夾和子文件夾中的每個文件上運行。

    非常感謝

  • 嘗試這個,

    import os
    from os.path import walk
    
    mydict = {"</b>":"</strong>", "</a>":"</h>", "<p>":"</p>"}
    
    for (path, dirs, files) in os.walk('./'):
        for f in files:
            if f.endswith('.html'):
                filepath = os.path.join(path,f)
                s = open(filepath).read()
                for k, v in mydict.iteritems():
                    s = s.replace(k, v)
                f = open(filepath, 'w')
                f.write(s)
                f.close()
    

    你可以將os.walk('./')更改為os.walk('/anyFolder/')

    使用glob模塊獲取*.html文件列表。

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM