【问题标题】:find and replace string from multiple files in a folder using python使用python从文件夹中的多个文件中查找和替换字符串
【发布时间】:2018-04-26 07:37:55
【问题描述】:

我想查找字符串,例如我的文件夹文件中的“Version1”包含多个“.c”和“.h”文件,并使用python文件将其替换为“Version2.2.1”。

有人知道这是怎么做到的吗?

【问题讨论】:

    标签: python string directory find-replace


    【解决方案1】:

    这是一个使用 os、glob 和 ntpath 的解决方案。结果保存在名为“输出”的目录中。你需要把它放在你有 .c 和 .h 文件的目录中并运行它。

    创建一个名为 output 的单独目录并将编辑后的文件放在那里:

    import glob
    import ntpath
    import os
    
    output_dir = "output"
    
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    for f in glob.glob("*.[ch]"):
        with open(f, 'r') as inputfile:
            with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w') as outputfile:
                for line in inputfile:
                    outputfile.write(line.replace('Version1', 'Version2.2.1'))
    

    替换字符串就地

    重要!请确保在运行之前备份您的文件:

    import glob
    
    for f in glob.glob("*.[ch]"):
        with open(f, "r") as inputfile:
            newText = inputfile.read().replace('Version1', 'Version2.2.1')
    
        with open(f, "w") as outputfile:
            outputfile.write(newText)
    

    【讨论】:

    • 我试过你的代码。我把我的目录路径而不是“输出”放在我所有文件所在的文件夹中。但是当我运行你的代码时,文件的所有内容都被删除了。不知道为什么?
    • 你不需要把你的目录路径代替输出。请将此脚本与您的 .c 和 .h 文件放在文件夹中并运行它。
    • 感谢 Ashish 有效。但是创建了另一个名为“输出”的目录。但我希望在同一个目录文件中进行更改。不想创建另一个目录
    • 如果我们创建一个名为 "output" 的临时文件,复制该目录中所有文件的数据并将其粘贴到我们的原始目录中,其中存在 'Version1' 字符串。然后删除这个临时文件“输出”
    • @Meera,按要求添加了原地替换代码。
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2018-09-17
    相关资源
    最近更新 更多