Search code examples
pythonstringdirectoryfind-replace

find and replace string from multiple files in a folder using python


I want to find string e.g. "Version1" from my files of a folder which contains multiple ".c" and ".h" files in it and replace it with "Version2.2.1" using python file.

Anyone know how this can be done?


Solution

  • Here's a solution using os, glob and ntpath. The results are saved in a directory called "output". You need to put this in the directory where you have the .c and .h files and run it.

    Create a separate directory called output and put the edited files there:

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

    Replace strings in place:

    IMPORTANT! Please make sure to back up your files before running this:

    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)