splitfile.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import ast
  2. import os
  3. from utils.fileio import walk_files
  4. def write_content_to_file(content, file_path):
  5. if not os.path.exists(file_path[:file_path.rindex("/")]):
  6. os.makedirs(file_path[:file_path.rindex("/")])
  7. if not os.path.exists(file_path[:file_path.rindex("\\")]):
  8. os.makedirs(file_path[:file_path.rindex("\\")])
  9. with open(file_path, 'w') as file_out:
  10. file_out.write(content)
  11. def split_file(file_dir, output_dir, endpoint=".py"):
  12. if not os.path.exists(output_dir):
  13. os.makedirs(output_dir)
  14. for file_path in walk_files(file_dir, endpoint):
  15. with open(file_path, 'r',encoding='utf8') as file:
  16. content = file.read()
  17. try:
  18. root = ast.parse(content)
  19. except Exception as e:
  20. print("错误明细:", e.__class__.__name__, e, file_path)
  21. continue
  22. file_id = 1
  23. for node in root.body:
  24. if isinstance(node, ast.FunctionDef):
  25. new_file_name = file_path.replace(file_dir, output_dir).replace(".py", "_" + str(file_id) + ".py")
  26. write_content_to_file(ast.get_source_segment(content, node), new_file_name)
  27. file_id += 1
  28. elif isinstance(node, ast.ClassDef):
  29. for son in node.body:
  30. if isinstance(son, ast.FunctionDef):
  31. new_file_name = file_path.replace(file_dir, output_dir).replace(".py",
  32. "_" + str(file_id) + ".py")
  33. write_content_to_file(ast.get_source_segment(content, son), new_file_name)
  34. file_id += 1
  35. if __name__ == '__main__':
  36. split_file("/Users/liufan/program/PYTHON/sap2nd/Data/archive/new2", "../target/archive/new2")