Scans all files and their subfolders in the specified folder path.
For each file, it deletes lines containing a specific definition. This deletion continues until the end of the defined block and correctly handles nested ifdef blocks.
Errors that may occur during opening, processing and rewriting of files are caught.
Code
- import os
- def search_and_delete(folder_path, target_define):
- for folder, subfolders, files in os.walk(folder_path):
- for file in files:
- file_path = os.path.join(folder, file)
- try:
- with open(file_path, 'r') as f:
- lines = f.readlines()
- new_content = []
- deletion_mode = False # To track nested ifdef blocks
- ifdef_counter = 0 # To count nested ifdef blocks
- for line in lines:
- if target_define in line: # Found the target define
- deletion_mode = True
- if deletion_mode and line.strip().startswith("#ifdef"): # Check nested ifdef blocks
- ifdef_counter += 1
- if deletion_mode and ifdef_counter > 0: # Inside a nested ifdef block
- if line.strip().startswith("#endif"): # Found the end of a nested ifdef
- ifdef_counter -= 1
- if ifdef_counter == 0: # Found the end of the nested ifdef block
- deletion_mode = False
- continue
- if not deletion_mode or target_define in line: # Not in deletion mode or the line contains the target define
- new_content.append(line)
- with open(file_path, 'w') as f:
- f.writelines(new_content)
- except Exception as e:
- print(f"Error: An error occurred while processing {file_path}: {e}")
- folder_path = input("Please enter the folder path: ")
- target_define = input("Please enter the target define to be deleted: ")
- search_and_delete(folder_path, target_define)