Python3 CRC32 File Calculation: Code Example and Explanation
Here is an example Python3 code to calculate the CRC32 value of a file:
import zlib
def crc32_file(file_path):
'Calculate the CRC32 value of a file'
with open(file_path, 'rb') as f:
crc = 0
while True:
chunk = f.read(1024)
if not chunk:
break
crc = zlib.crc32(chunk, crc)
return crc & 0xffffffff # Ensure the result is unsigned
# Example usage
file_path = 'example_file.txt'
crc32 = crc32_file(file_path)
print(f'CRC32 value of file '{file_path}': {crc32}')
In this code, we open the file in binary mode and read it in 1024 byte chunks. For each chunk, we update the CRC32 value using the zlib.crc32 function, which returns a signed integer. To ensure the result is unsigned, we perform a bitwise AND with 0xffffffff.
Note that this code assumes the file exists and can be read. You may want to add error handling for cases where the file does not exist or cannot be read.
原文地址: https://www.cveoy.top/t/topic/nRT2 著作权归作者所有。请勿转载和采集!