Skip to main content

How to replace a specific string in a file in Python

How to replace a specific string in a file in Python.

Here's a step-by-step tutorial on how to replace a specific string in a file using Python:

  1. Import the necessary modules:

    import fileinput
    import sys
  2. Define a function to perform the replacement:

    def replace_string(file_path, search_string, replace_string):
    # Open the file in read mode
    with fileinput.FileInput(file_path, inplace=True, backup='.bak') as file:
    for line in file:
    # Replace the search string with the replace string
    updated_line = line.replace(search_string, replace_string)
    # Write the updated line to the file
    sys.stdout.write(updated_line)

    In this function, we use the fileinput module to read the file line by line and make changes in-place. The inplace=True argument ensures that the changes are made directly to the file. The backup='.bak' argument creates a backup of the original file with a ".bak" extension.

  3. Call the replace_string function with the appropriate arguments:

    replace_string('path/to/file.txt', 'search_string', 'replace_string')

    Replace 'path/to/file.txt' with the actual path to the file you want to modify. Replace 'search_string' with the string you want to replace, and 'replace_string' with the string you want to replace it with.

    Example:

    replace_string('data.txt', 'apple', 'orange')

    This example will replace all occurrences of the word "apple" with the word "orange" in the file named "data.txt".

And that's it! You have now successfully replaced a specific string in a file using Python.