我正在尝试将MPEG-2 TS文件转换为字节模式文件,并在Python3中的188个字节的数据包之间放置某种分隔符。这是我的代码:
def hex_conversion(inp_tsfile):
with open(inp_tsfile, 'rb') as f:
with open(out_hexfile, 'wb') as f_out:
for packet in iter(lambda: f.read(188), b''):
line = packet + codecs.encode("\n", 'utf-8')
f_out.write(codecs.encode(line, 'hex'))
不幸的是,这段代码没有放置新的行分隔符,因此文件看起来不间断,因此我无法可靠地grep查找其中的字符串。如果我从f_out_write
切换到print()
并执行手动将stdout
转发到文件的脚本,则格式正确。
[EDIT]:我想在文件中包含以下内容:
b'4700ff16d88afc34c6790be7abe766bc7669e9ad7c544f5f713c6d20e7866a76972eb96100f70618c5c8000d9f35f013760abda7f4e57db8f31ac1e14e16e31b33c6d44cbb7ecc20f97cebc4e8c6001573271c4460ec5c5336570b81f2d642251c6f4379f7c7ca694446751d19c3f5663ff809342f80f6244fae30d19fc16e7df860ca0b397c34385a35c33814e5770ef7218dda48c43e991fd55f8cd4406fa1cb8a3e536292f5fa0ef841972c9513784648924f039961ba1c9a7b600a'
b'471fff10f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabac0a'
b'4700ff1731febdc7a2a34d6ce7b87922094b65e689887c151fe62cfcd6b74d1ea4e00a5f9a192b0e3d17e2b880027daa1336b953088bdf9303ef70783fcd49372dd48017404423646d65e00a31ef2b5cc033704a1ef31ff2c8e76cd9d3e19ae49abef8ea3d38d3db5093774ed3de3838b9e9d5eb63d4d67f4c4d081fa75e3062811f4bcb748b66f8f165292ffb9f48f90337ca26b3bd232a635fd7c0275abaf4a812f17bbaba3d51218628acfc540f68453f6f330cf5cd15d6647a840a'
因此,如您所见,我在每一行上都有一个新数据包。如果我执行print(codecs.encode(line, 'hex'))
命令,这实际上是输出。而是,我的文件没有分隔数据包。
答案 0 :(得分:0)
所以我已经弄清楚了如何在@ mkrieger1的帮助下做到这一点:
def hex_conversion(inp_tsfile):
with open(inp_tsfile, 'rb') as f:
with open(out_hexfile, 'w') as f_out:
for chunk in iter(lambda: f.read(188), b''):
pkt_hex = codecs.encode(chunk, 'hex')
line = str(pkt_hex) + "\n"
f_out.write(line)