Skip to content

Instantly share code, notes, and snippets.

@lsferreira42
Created March 22, 2023 02:03
Show Gist options
  • Save lsferreira42/e835d715715c0a92e31fc3fbc43bbf98 to your computer and use it in GitHub Desktop.
Save lsferreira42/e835d715715c0a92e31fc3fbc43bbf98 to your computer and use it in GitHub Desktop.
create a python script that rename import modules using AST
import ast
import os
def rename_import_modules(source_file, old_module_name, new_module_name):
# Parse the source code into an Abstract Syntax Tree (AST)
with open(source_file) as f:
source = f.read()
tree = ast.parse(source)
# Traverse the AST to find import statements and update the module name
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name == old_module_name:
alias.name = new_module_name
# Write the updated code to a new file
new_file = os.path.splitext(source_file)[0] + '_new.py'
with open(new_file, 'w') as f:
f.write(ast.unparse(tree))
# Example usage:
rename_import_modules('example.py', 'old_module_name', 'new_module_name')
@lsferreira42
Copy link
Author

lsferreira42 commented Mar 22, 2023

create a python script that rename import packages using AST

import ast
import os

def rename_import_packages(source_file, old_package_name, new_package_name):
    # Parse the source code into an Abstract Syntax Tree (AST)
    with open(source_file) as f:
        source = f.read()
    tree = ast.parse(source)

    # Traverse the AST to find import statements and update the package name
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            if node.module.startswith(old_package_name):
                node.module = node.module.replace(old_package_name, new_package_name)

    # Write the updated code to a new file
    new_file = os.path.splitext(source_file)[0] + '_new.py'
    with open(new_file, 'w') as f:
        f.write(ast.unparse(tree))

# Example usage:
rename_import_packages('example.py', 'old_package_name', 'new_package_name')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment