Change the a parameter or name of the function all over the .py files

Question:

I have the different .py files (~10). For example, here is two function in two different .py files. So, I want to change the parameter b to c, and the name of function sum to new_name and I want to change them all over the other .py files. Do we have any option in python for that:

f1.py:

def sum(a,b):
 return a+b

f2.py:

import f1
def foo(a,b):
 return a+2*b + sum(a,b)

The code which I want is output:

f1.py:

def new_name(a,c):
 return a+c 

f2.py:

def foo(a,c):
 return a+2*c + new_name(a,c)
Asked By: Sadcow

||

Answers:

Not sure what you are looking for, i.e. IDE vs a Python-based solution, but here is a small script you can use to iterate over the files in your directory, open them, search and replace text. This could be finnicky to work with though, depending on the contents of your file:

import os

def replace_in_file(file_path):
    with open(file_path, 'r') as f:
        file_contents = f.read()

    # Replace occurrences of 'sum' with 'new_name' and 'b' with 'c' per OP instructions
    new_contents = file_contents.replace('sum(', 'new_name(').replace(', b', ', c')

    with open(file_path, 'w') as f:
        f.write(new_contents)

# Directory containing the .py files
directory = '/path/to/directory'

# Loop over all .py files in the directory
for filename in os.listdir(directory):
    if filename.endswith('.py'):
        file_path = os.path.join(directory, filename)
        replace_in_file(file_path)
Answered By: artemis
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.