1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- import os
- def reduce_bin_file_size(relative_path, target_size):
- """
- 将相对路径下的 bin 文件减小至固定大小。
- :param relative_path: bin 文件的相对路径
- :param target_size: 目标文件大小(字节)
- """
- # 获取当前工作目录
- current_path = os.getcwd()
- # 获取上一级目录
- parent_directory = os.path.dirname(current_path)
-
- file_path = os.path.join(parent_directory,relative_path)
- # 检查文件是否存在
- if not os.path.isfile(file_path):
- print(f"文件 {file_path} 不存在。")
- return
- # 获取文件大小
- file_size = os.path.getsize(file_path)
- print(f"原始文件大小: {file_size} 字节")
- # 如果文件大小已经小于或等于目标大小,则不需要处理
- if file_size <= target_size:
- print(f"文件大小已经小于或等于目标大小 {target_size} 字节,无需处理。")
- return
- # 读取文件内容
- with open(file_path, 'rb') as file:
- data = file.read(target_size)
- # 写入原文件
- with open(file_path, 'wb') as file:
- file.write(data)
- print(f"新文件已创建: {new_file_path},大小: {target_size} 字节")
- # 示例用法
- relative_path = 'Debug/Exe/MC_CITY-36V_V1.1.0_20250315.bin' # 替换为你的 bin 文件相对路径
- target_size = 116*1024 # 目标文件大小(字节),例如 1024 字节
- reduce_bin_file_size(relative_path, target_size)
|