Created
February 15, 2025 12:25
-
-
Save robes7/fa6e7c827b622c02b691b71030fc0b22 to your computer and use it in GitHub Desktop.
File text replacer
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 os | |
| def replace_text_in_file(file_path, search_text, replace_text, edited_lines): | |
| try: | |
| with open(file_path, 'r', encoding='utf-8', errors='ignore') as file: | |
| lines = file.readlines() | |
| modified = False | |
| new_lines = [] | |
| for i, line in enumerate(lines): | |
| if search_text in line: | |
| new_lines.append(line.replace(search_text, replace_text)) | |
| edited_lines.append(f"{file_path}: Line {i+1}") | |
| modified = True | |
| else: | |
| new_lines.append(line) | |
| if modified: | |
| with open(file_path, 'w', encoding='utf-8', errors='ignore') as file: | |
| file.writelines(new_lines) | |
| print(f"Updated: {file_path}") | |
| except Exception as e: | |
| print(f"Error processing {file_path}: {e}") | |
| def replace_text_in_directory(directory, search_text, replace_text): | |
| edited_lines = [] | |
| for root, _, files in os.walk(directory): | |
| for file in files: | |
| file_path = os.path.join(root, file) | |
| replace_text_in_file(file_path, search_text, replace_text, edited_lines) | |
| if edited_lines: | |
| print("\nSummary of edits:") | |
| for line in edited_lines: | |
| print(line) | |
| else: | |
| print("No changes made.") | |
| def main(): | |
| directory = os.path.dirname(os.path.abspath(__file__)) | |
| search_text = input("Enter the text to replace: ") | |
| replace_text = input("Enter the replacement text: ") | |
| replace_text_in_directory(directory, search_text, replace_text) | |
| print("Replacement complete.") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment