""" 工程文件处理方法 """ from watermark_generate.exceptions import BusinessException def replace_block_in_file(file_path, old_block, new_block): """ 修改指定文件的代码块 :param file_path: 待修改的文件路径 :param old_block: 原始代码块 :param new_block: 修改后的代码块 :return: """ # 读取文件内容 with open(file_path, "r") as file: file_content_str = file.read() file_content_str = file_content_str.replace(old_block, new_block) # 写回文件 with open(file_path, 'w', encoding='utf-8') as file: file.write(file_content_str) def append_block_in_file(file_path, new_block): """ 向文件末尾追加代码块 :param file_path: 待修改的文件路径 :param new_block: 追加的代码块 :return: """ try: with open(file_path, 'a') as file: file.write('\n' + new_block) except Exception as e: raise BusinessException(message=f"追加文件内容失败, {e}", code=-1) def insert_code_after_line(file_path, line_number, code_block): # 读取文件内容 with open(file_path, 'r') as file: lines = file.readlines() # 确保 line_number 合法 if line_number < 1 or line_number > len(lines): print(f"Line number {line_number} is out of range.") return # 将代码块拆分成多行 code_lines = code_block.splitlines(True) # 在指定行后插入代码块 lines[line_number:line_number] = code_lines # 写回文件 with open(file_path, 'w') as file: file.writelines(lines)