[英]How to read the exact bytes of the file?
import sys
def XoR(filename, operand):
byte = bytearray(1024)
with open(filename, "rb") as file:
reAd = file.readinto(byte)
while True:
reAd = file.readinto(byte)
for i in range(reAd):
byte[i] ^= operand
sys.stdout.buffer.write(byte)
def main():
return XoR(sys.argv[1], int(sys.argv[2]))
if __name__ == '__main__':
main()
我不確定如何修改代碼,以使輸出的字節總數與輸入文件中的字節總數完全相同。 根據我的代碼,輸出為1024的倍數,即緩沖區的初始大小。 我該怎么辦,以便它在最后一塊而不是整個緩沖區中輸出相關字節? 我應該創建一個條件來處理最后一個塊嗎?
選項1:僅將與readinto
操作返回的字節一樣多的字節寫回文件。
sys.stdout.buffer.write(byte[:reAd])
選項2:不要使用readinto
。
def XoR(filename, operand): with open(filename, "rb") as file: while True: chunk = file.read(1024) if not chunk: break chunk = bytes(byte ^ operand for byte in chunk) sys.stdout.buffer.write(chunk)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.