保存并重新加载后,为什么两个文件的大小不同?

时间:2014-08-13 14:31:38

标签: python dos

我将Pygame与StringIO结合使用,可以从同一个源创建两个文件。它们看起来大小不一;为什么?

import pygame
import StringIO

putimage = pygame.image.load("88keykbd.png")
buff = StringIO.StringIO()
buff.name = '88keykbd.png'

pygame.image.save(putimage, buff)

putimage = buff.getvalue()
print "buff:", type(buff), "myimage:", type(putimage), "getimage:", type(putimage)

print len(putimage) # 110564
with open('myscrambledimage.dat', 'w') as newfile:
    newfile.write(putimage)

with open('myscrambledimage.dat', 'r') as newfile:
    getimage= newfile.read()
print len(getimage) # 7502

1 个答案:

答案 0 :(得分:2)

您应该对文件使用二进制访问:

with open('myscrambledimage.dat', 'wb') as newfile:
    newfile.write(putimage)

with open('myscrambledimage.dat', 'rb') as newfile:
    getimage= newfile.read()

当你这样做时,尺寸是一致的。除了行结尾,Windows(例如)将CTRL + Z字符视为EOF。