modify_file.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. 工程文件处理方法
  3. """
  4. from watermark_generate.exceptions import BusinessException
  5. def replace_block_in_file(file_path, old_block, new_block):
  6. """
  7. 修改指定文件的代码块
  8. :param file_path: 待修改的文件路径
  9. :param old_block: 原始代码块
  10. :param new_block: 修改后的代码块
  11. :return:
  12. """
  13. # 读取文件内容
  14. with open(file_path, "r") as file:
  15. file_content_str = file.read()
  16. file_content_str = file_content_str.replace(old_block, new_block)
  17. # 写回文件
  18. with open(file_path, 'w', encoding='utf-8') as file:
  19. file.write(file_content_str)
  20. def append_block_in_file(file_path, new_block):
  21. """
  22. 向文件末尾追加代码块
  23. :param file_path: 待修改的文件路径
  24. :param new_block: 追加的代码块
  25. :return:
  26. """
  27. try:
  28. with open(file_path, 'a') as file:
  29. file.write('\n' + new_block)
  30. except Exception as e:
  31. raise BusinessException(message=f"追加文件内容失败, {e}", code=-1)
  32. def insert_code_after_line(file_path, line_number, code_block):
  33. # 读取文件内容
  34. with open(file_path, 'r') as file:
  35. lines = file.readlines()
  36. # 确保 line_number 合法
  37. if line_number < 1 or line_number > len(lines):
  38. print(f"Line number {line_number} is out of range.")
  39. return
  40. # 将代码块拆分成多行
  41. code_lines = code_block.splitlines(True)
  42. # 在指定行后插入代码块
  43. lines[line_number:line_number] = code_lines
  44. # 写回文件
  45. with open(file_path, 'w') as file:
  46. file.writelines(lines)