gpt4 book ai didi

python - 向文件写入的数据多于读取的数据?

转载 作者:行者123 更新时间:2023-12-01 04:00:20 26 4
gpt4 key购买 nike

我目前正在试验 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() .

最佳答案

这是一个您可能希望使用的简单示例:

import sys

f = open('gash.txt', 'rb')
stuff=f.read() # stuff refers to a bytes object
f.close()

print(stuff)

f2 = open('gash2.txt', 'wb')

for i in stuff:
f2.write(i.to_bytes(1, sys.byteorder))

f2.close()

如您所见,bytes 对象是可迭代的,但在 for 循环中,我们在 i 中返回一个 int。要将其转换为字节,我使用 int.to_bytes() 方法。

关于python - 向文件写入的数据多于读取的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com