美文网首页
python转换bin文件大小端

python转换bin文件大小端

作者: 风铃草613 | 来源:发表于2019-08-02 16:22 被阅读0次

需求:将当前文件夹下所有源文件(小端存储的bin文件)转换成目标文件(大端存储的bin文件),或者大端转小端,目标文件文件名加特殊后缀,防止再次运行时将生成的目标文件再次转换

# 大小端转换.py
import os
import struct

TARGET_FEATURE = "_lz"

def get_size(file):
    return os.path.getsize(file)

def get_fmt(num, is_source_file=True):
    if is_source_file:
        return ">"+int(size/4)*"I"
    else:
        return "<"+int(size/4)*"I"

def get_uint16_fmt(num, is_source_file=True):
    if is_source_file:
        return ">"+int(num/2)*"H"
    else:
        return "<"+int(num/2)*"H"

def get_size_by_fmt(fmt):
    return struct.calcsize(fmt)

def get_target_file(file):
    file_name, file_fmt = file.rsplit(".")
    return file_name + TARGET_FEATURE + "." + file_fmt

def is_source_file(file):
    if 1 != file.count("."):
        return False

    file_name, _ = file.split(".")

    if file_name.endswith(TARGET_FEATURE):
        return False
    return file.endswith(".bin")

def endian_trans(source_file, size):
    source_fmt = get_uint16_fmt(size)
    dst_fmt = get_uint16_fmt(size, False)
    dst_file = get_target_file(source_file)
    with open(source_file, "rb") as f:
        content = struct.unpack(source_fmt, f.read(size))
        target = struct.pack(dst_fmt, *content)
        with open(dst_file, "wb") as f_1:
            f_1.write(target)

if __name__ == '__main__':
    for item in os.listdir("."):
        if is_source_file(item):
            size = get_size(item)
            source_fmt = get_fmt(size)
            assert size == get_size_by_fmt(source_fmt), item+" convert error"
            endian_trans(item, size)

单元测试

import unittest
from 大小端转换 import *


class MtTest(unittest.TestCase):
    # # 每个测试用例执行之前做操作
    # def setUp(self):
    #     print("setUp")

    # # 每个测试用例执行之后做操作
    # def tearDown(self):
    #     print("tearDown")

    # # 必须使用 @ classmethod装饰器, 所有test运行完后运行一次
    # @classmethod
    # def tearDownClass(self):
    #     print("tearDownClass")

    # # 必须使用@classmethod 装饰器,所有test运行前运行一次
    # @classmethod
    # def setUpClass(self):
    #     print("setUpClass")

    def test_get_target_file(self):
        file = "C:/Users/lz/Desktop/readme.txt"
        target_file = "C:/Users/lz/Desktop/readme_lz.txt"
        self.assertEqual(get_target_file(file), target_file)

    def test_is_source_file(self):
        self.assertFalse(is_source_file("test"))

    def test_is_source_file_1(self):
        self.assertTrue(is_source_file("C:/test.bin"))

    def test_is_source_file_2(self):
        self.assertFalse(is_source_file("C:/test.dat"))


if __name__ == '__main__':
    unittest.main() #运行所有的测试用例

相关文章

网友评论

      本文标题:python转换bin文件大小端

      本文链接:https://www.haomeiwen.com/subject/mpmfdctx.html