简体   繁体   English

在Python中运行多个查找和替换(在文件夹和子文件夹中的每个文件上)

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

I have a folder (courses) with sub-folders and a random number of files. 我有一个文件夹(课程),包含子文件夹和随机数量的文件。 I want to run multiple search and replaces on those random files. 我想运行多个搜索并替换这些随机文件。 Is it possible to do a wild card search for .html and have the replaces run on every html file ? 是否可以对.html进行通配符搜索并在每个html文件上运行替换?

Search and replaces: 搜索和替换:

  • 1) "</b>" to "</strong>" 1) "</b>""</strong>"
  • 2) "</a>" to "</h>" 2) "</a>""</h>"
  • 3) "<p>" to "</p>" 3) "<p>""</p>"
  • Also all these replaces have to be run on every file in the folder and sub-folders. 此外,所有这些替换都必须在文件夹和子文件夹中的每个文件上运行。

    Thank you so much 非常感谢

  • Try this, 尝试这个,

    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()
    

    You can change os.walk('./') to os.walk('/anyFolder/') 你可以将os.walk('./')更改为os.walk('/anyFolder/')

    使用glob模块获取*.html文件列表。

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM