reduce_bin.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. def reduce_bin_file_size(relative_path, target_size):
  3. """
  4. 将相对路径下的 bin 文件减小至固定大小。
  5. :param relative_path: bin 文件的相对路径
  6. :param target_size: 目标文件大小(字节)
  7. """
  8. # 获取当前工作目录
  9. current_path = os.getcwd()
  10. # 获取上一级目录
  11. parent_directory = os.path.dirname(current_path)
  12. file_path = os.path.join(parent_directory,relative_path)
  13. # 检查文件是否存在
  14. if not os.path.isfile(file_path):
  15. print(f"文件 {file_path} 不存在。")
  16. return
  17. # 获取文件大小
  18. file_size = os.path.getsize(file_path)
  19. print(f"原始文件大小: {file_size} 字节")
  20. # 如果文件大小已经小于或等于目标大小,则不需要处理
  21. if file_size <= target_size:
  22. print(f"文件大小已经小于或等于目标大小 {target_size} 字节,无需处理。")
  23. return
  24. # 读取文件内容
  25. with open(file_path, 'rb') as file:
  26. data = file.read(target_size)
  27. # 写入原文件
  28. with open(file_path, 'wb') as file:
  29. file.write(data)
  30. print(f"新文件已创建: {new_file_path},大小: {target_size} 字节")
  31. # 示例用法
  32. relative_path = 'Debug/Exe/MC_CITY-36V_V1.1.0_20250315.bin' # 替换为你的 bin 文件相对路径
  33. target_size = 116*1024 # 目标文件大小(字节),例如 1024 字节
  34. reduce_bin_file_size(relative_path, target_size)