splitfile.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. with open(file_path, 'w') as file_out:
  8. file_out.write(content)
  9. def split_file(file_dir, output_dir, endpoint=".py"):
  10. if not os.path.exists(output_dir):
  11. os.makedirs(output_dir)
  12. for file_path in walk_files(file_dir, endpoint):
  13. with open(file_path, 'r') as file:
  14. content = file.read()
  15. try:
  16. root = ast.parse(content)
  17. except Exception as e:
  18. print("错误明细:", e.__class__.__name__, e, file_path)
  19. continue
  20. file_id = 1
  21. for node in root.body:
  22. if isinstance(node, ast.FunctionDef):
  23. new_file_name = file_path.replace(file_dir, output_dir).replace(".py", "_" + str(file_id) + ".py")
  24. write_content_to_file(ast.get_source_segment(content, node), new_file_name)
  25. file_id += 1
  26. elif isinstance(node, ast.ClassDef):
  27. for son in node.body:
  28. if isinstance(son, ast.FunctionDef):
  29. new_file_name = file_path.replace(file_dir, output_dir).replace(".py",
  30. "_" + str(file_id) + ".py")
  31. write_content_to_file(ast.get_source_segment(content, son), new_file_name)
  32. file_id += 1
  33. if __name__ == '__main__':
  34. split_file("/Users/liufan/program/PYTHON/sap2nd/Data/archive", "../target/archive")