![](/img/trans.png)
[英]Why does my code work in python shell but not when I double click the py file
[英]Why does this python code double the size of my file without changing it?
基本上,我只是想在编辑文件后将字符串写出到文件中,并且作为概念验证,我只是在尝试进行无意义的更改。 但是,如下面的示例所示,由于某种原因,即使这样也会使输出大小增加一倍。 有人知道为什么会这样吗?
content = StringIO.getvalue()
with open("real.png", 'wb') as dump:
dump.write(content) #35KB
content = [str(ord(char)) for char in content]
content = "".join([hex(int(char)).lstrip("0x").zfill(2) for char in content])
with open("new.png", "wb") as dump:
dump.write(content) #70KB
您正在将每个字节转换为2个字节的字符串,该字符串表示该字节的十六进制值。 十六进制字符串表示是不一样的东西作为原始字节。
如果文件大小不加倍,我会感到非常惊讶。
如果使用HEX编辑器查看将字节显示为十六进制字符的原始图像,则会使该数据的一个编辑器表示形式与文件的实际内容混淆。
如果您想更有效地完成该任务,则可以使用binascii.hexlify()
函数以更少的代码完成它。 镜像操作称为binascii.unhexlify()
:
from binascii import hexlify, unhexlify
content = StringIO.getvalue()
hex_content = hexlify(content)
same_content = unhexlify(hex_content)
assert content == same_content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.