Created
March 22, 2023 02:03
-
-
Save lsferreira42/e835d715715c0a92e31fc3fbc43bbf98 to your computer and use it in GitHub Desktop.
create a python script that rename import modules using AST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
create a python script that rename import packages using AST