以下是我的問題重新措辭Python的讀取和寫入到二進制文件
讀前10個字節的二進制文件(操作後) -
infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)
for i in x:
print(i, end=', ')
print(x)
outfile.write(bytes(x, "UTF-8"))
第一個print語句讓 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二打印語句使 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
x的值的十六進制解釋。
outfile.write(bytes(x, "UTF-8"))
回報 -
那麼x不能是普通的字符串,而是一個字節串,這仍然是迭代?
如果我想寫x的內容outfile.jpg不變的話,我去 -
outfile.write(x)
現在我試圖把每個x [i]和執行上的每個部分的操作(如下圖所示爲1)的簡單骨骼產品,將值賦給y並將y寫入outfile.jpg,使其與infile.jpg相同。所以我嘗試 -
infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)
yi = len(x)
y = [0 for i in range(yi)]
j = 0
for i in x:
y [j] = i*1
j += 1
for i in x:
print(i, end=', ')
print(x)
for i in y:
print(i, end=', ')
print(y)
print(repr(x))
print(repr(y))
outfile.write(y)
第一個print語句(通過X迭代)讓 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二打印語句使 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
第三個print語句(至Y迭代)給出 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
print語句給人 -
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
最後,印刷再版(x)和再版(Y),由Tim的建議,給了分別 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
和文件寫入聲明爲錯誤 -
TypeError: 'list' does not support the buffer interface
我需要的是y以具有相同的類型爲x使得outfile.write(X)= outfile.write(Y)
我盯着Python的眼睛,但我仍然沒有看到它的靈魂。
看看這篇文章:http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface似乎是在Python 2和Python 3之間改變了String類。 –
Hunter - 我用outfile.write(s.encode('UTF-8')替換了outfile.write(s)並且沒有收到任何錯誤!但是使用infile.read()導致outfile.jpg的大小是infile的兩倍。 jpg和破壞我想要完成的是讀取二進制文件,執行操作,反轉該操作並將輸出寫入單獨的文件以使它們完全相同 – brett
在後面的答案中,我鏈接了使用的'outfile.write (bytes(s,「UTF-8」));' –