From c7bf51941b691eea3cb8536d0f4e18427ba916e8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 2 Jan 2024 21:22:26 +0100 Subject: [PATCH] Optimized string replace to catch utf8 errors --- replace_string.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/replace_string.py b/replace_string.py index 55e0681..04f901d 100644 --- a/replace_string.py +++ b/replace_string.py @@ -2,17 +2,21 @@ import os import argparse def replace_content(path, old_string, new_string, preview, verbose): - with open(path, 'r', encoding='utf-8') as f: - content = f.read() + try: + with open(path, 'r', encoding='utf-8') as f: + content = f.read() - if old_string in content: - new_content = content.replace(old_string, new_string) - - print_verbose(f"Replacing content in: {path}",verbose) + if old_string in content: + new_content = content.replace(old_string, new_string) - if not preview: - with open(path, 'w', encoding='utf-8') as f: - f.write(new_content) + print_verbose(f"Replacing content in: {path}", verbose) + + if not preview: + with open(path, 'w', encoding='utf-8') as f: + f.write(new_content) + + except UnicodeDecodeError as e: + print_verbose(f"Warning: Unicode decode error encountered in file {path}. Skipping file.", verbose) def print_verbose(content,verbose): if verbose: