From 5cbf98a926cf4e28f589ed2e0cee4cb85fd5b17b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 22 Aug 2023 23:58:37 +0200 Subject: [PATCH] Solved bug --- replace_string.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/replace_string.py b/replace_string.py index 3d6d034..9d63bee 100644 --- a/replace_string.py +++ b/replace_string.py @@ -5,7 +5,7 @@ def replace_content(path, old_string, new_string, preview, verbose): with open(path, 'r', encoding='utf-8') as f: content = f.read() - if old_string in content: # Prüfen, ob der alte String im Inhalt vorkommt + if old_string in content: new_content = content.replace(old_string, new_string) if verbose: @@ -16,6 +16,9 @@ def replace_content(path, old_string, new_string, preview, verbose): f.write(new_content) def process_directory(base_path, old_string, new_string, recursive, folder, files, content, preview, verbose, hidden): + # Eine Liste, um die Pfade der umzubenennenden Ordner zu speichern + directories_to_rename = [] + for root, dirs, filenames in os.walk(base_path): # Wenn "hidden" nicht gesetzt ist, versteckte Dateien/Ordner aus der Liste entfernen if not hidden: @@ -35,20 +38,25 @@ def process_directory(base_path, old_string, new_string, recursive, folder, file print(f"Renaming file from: {old_path} to: {new_path}") if not preview: os.rename(old_path, new_path) - + + # Pfade von zu ändernden Ordnern speichern if folder: for d in dirs: if old_string in d: old_path = os.path.join(root, d) new_path = os.path.join(root, d.replace(old_string, new_string)) - if verbose: - print(f"Renaming directory from: {old_path} to: {new_path}") - if not preview: - os.rename(old_path, new_path) - + directories_to_rename.append((old_path, new_path)) + if not recursive: break + # Ordnernamen ändern nach dem os.walk() Durchlauf + for old_path, new_path in directories_to_rename: + if verbose: + print(f"Renaming directory from: {old_path} to: {new_path}") + if not preview: + os.rename(old_path, new_path) + def main(): parser = argparse.ArgumentParser(description="Replace strings in directories and files.") parser.add_argument('path', help="Path in which replacements should be made.")