2 回答

TA貢獻1884條經驗 獲得超4個贊
那么如何解決這個問題。
正如 Cyril Jouve 已經提到的,檢查是否有 file_data
你建議什么其他方法。
使用下面這種方法有什么副作用。
以 16 字節為單位的塊讀取相對較慢。我猜你有足夠的內存來讀取更大的塊,如 4096、8192 ...
除非您有非常大的文件和有限的磁盤空間,否則我認為在同一個文件中讀取和寫入沒有任何好處。如果發生錯誤并且操作系統已經將數據寫入磁盤,您將丟失原始數據,并且將得到一個不完整的加密文件,您不知道其中哪一部分被加密。
創建新的加密文件然后刪除并重命名(如果沒有錯誤)會更容易且更省錢。
加密到新文件,捕獲異常,檢查加密文件的存在和大小,僅在一切正常的情況下刪除源并重命名加密文件。
import os
path = r'D:\test.dat'
input_path = path
encrypt_path = path + '_encrypt'
try:
with open(input_path, "rb") as input_file:
with open(encrypt_path, "wb") as encrypt_file:
print("...ENCRYPTING")
while True:
file_data = input_file.read(4096)
if not file_data:
break
ciphertext = aes_enc.update(file_data)
encrypt_file.write(ciphertext)
print("...Complete...")
if os.path.exists(encrypt_path):
if os.path.getsize(input_path) == os.path.getsize(encrypt_path):
print(f'Deleting {input_path}')
os.remove(input_path)
print(f'Renaming {encrypt_path} to {input_path}')
os.rename(encrypt_path, input_path)
except Exception as e:
print(f'EXCEPTION: {str(e)}')

TA貢獻1803條經驗 獲得超3個贊
文件對象沒有“真實性”,因此您不能將其用作循環的條件。
當 read() 返回空字節對象時,文件位于 EOF ( https://docs.python.org/3/library/io.html#io.BufferedIOBase.read )
with open(path, "r+b") as file:
print("...ENCRYPTING")
while True:
file_data = file.read(16)
if not file_data:
break
ciphertext = aes_enc.update(file_data)
file.seek(-len(file_data), os.SEEK_CUR)
file.write(ciphertext)
print("...Complete...")
添加回答
舉報