繁体   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