【发布时间】:2017-06-25 18:19:02
【问题描述】:
我正在编写一个程序,它计算文件列表的校验和,然后将其与参考文件进行比较。
我正在尝试将 hashfile 方法中的字节缓冲区转换为与 os.stat(path).st_size 使用的单位相同的文件大小,以便我可以相应地更新 tqdm 进度条。 (试图实现最后一个例子here)
我尝试了很多东西(len(buf): 给我的处理大小远远大于总数,int.from_bytes(): OverflowError - int too large to convert to float, struct.unpack_from(buf): requires to read a single一个字节,各种转换字节的函数),但到目前为止没有任何效果。看来我对字节的理解不够,无法知道要搜索什么或实施我找到的解决方案。
这是代码的摘录:
import hashlib
import os
from tqdm import tqdm
# calculate total size to process
self.assets_size += os.stat(os.path.join(root, f)).st_size
def hashfile(self, progress, afile, hasher, blocksize=65536):
"""
Checksum buffer
:param progress: progress bar object
:param afile: file to process
:param hasher: checksum algorithm
:param blocksize: size of the buffer
:return: hash digest
"""
buf = afile.read(blocksize)
while len(buf) > 0:
self.processed_size += buf # need to convert from bytes to file size
hasher.update(buf)
progress.update(self.processed_size) # tqdm update
buf = afile.read(blocksize)
afile.seek(0)
return hasher.digest()
def process_file(self, progress, fichier):
"""
Checks if the file is in the reference dictionary;
If so, checks if the size of the file matches the one stored in the dictionary;
If so, calculates the checksum of the file and compares it to the one in the dictionary
:param progress: progress bar object
:param fichier: asset file to process
:return: string outcome of the process
"""
checksum = self.hashfile(progress, open(fichier, 'rb'), hashlib.sha1())
# check if checksum matches
return outcome
def main_process(self):
"""
Launches and monitors the process and writes a report of the results
:return: application end
"""
with tqdm(total=self.assets_size, unit='B', unit_scale=True) as pbar:
all_results = []
for f in self.assets.keys():
results = self.process_file(pbar, f)
all_results.append(results)
for r in all_results:
print(r)
【问题讨论】:
-
len(buf) 是要走的路。也许您没有在文件之间重置 self.processed_size?
-
@RadosławCybulski 感谢您为我指明正确的方向;例如,在文件之间重置
self.processed_size仍然会给我一个巨大的处理大小,而正在处理一个大文件。也许问题在于我在哪里更新处理后的大小,我会调查一下。 -
@RadosławCybulski 实际上我需要在 while 循环的每次迭代中重置处理后的大小......不知道为什么,但我会及时理解 ;-) 请作为答案发布,我会接受它,谢谢。
-
Nach,不需要,很高兴我能帮上忙。 :)
标签: python python-3.x size byte tqdm