我目前正在试验 Python 3 在读取和写入数据时如何处理字节,我遇到了一个特别令人不安的问题,我似乎无法找到其根源。我基本上是从 JPEG 文件中读取字节,使用 将它们转换为整数ord()
,然后使用该行将字节返回为其原始字符并将其chr(character).encode('utf-8')
写回 JPEG 文件。没问题吧?好吧,当我尝试打开 JPEG 文件时,我收到一条 Windows 8.1 通知,说它无法打开照片。当我检查这两个文件时,一个是 5.04MB,另一个是 7.63MB,这让我非常困惑。
def __main__():
operating_file = open('photo.jpg', 'rb')
while True:
data_chunk = operating_file.read(64*1024)
if len(data_chunk) == 0:
print('COMPLETE')
break
else:
new_operation = open('newFile.txt', 'ab')
for character in list(data_chunk):
new_operation.write(chr(character).encode('utf-8'))
if __name__ == '__main__':
__main__()
这是我正在使用的确切代码,关于正在发生的事情以及如何修复它的任何想法?
注意:我假设list(data_chunk)
提供的数字列表等同于ord()
.