2 回答
![?](http://img1.sycdn.imooc.com/54584cfb0001308402200220-100-100.jpg)
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)}')
![?](http://img1.sycdn.imooc.com/54584d6100015f5802200220-100-100.jpg)
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...")
添加回答
举报