问题描述
我想计算文件的并得到如下输出: E45A12AC
。这是我的代码:
$ b $ pre $ $ $ $ $ $ $ $ $ $ $ $ $ zlib
$ b $ def crc(fileName):
fd = open(fileName,rb)
content = fd.readlines()
fd.close()
for eachLine in content:
zlib.crc32(eachLine)
for sys.argv中的每个文件[1:]:
crc(eachFile)
这将计算每行的CRC,但它的输出(例如 -1767935985 $ c $
Hashlib以我想要的方式工作,但它计算md5:
pre $
import hashlib
m = hashlib.md5()
用于打开('data.txt','rb')行:
m.update (line)
print m.hexdigest()
是否可以使用类似的方法 zlib.crc32
?
/ p>
def crc(fileName):
prev = 0
对于打开的每个行(fileName,rb):
prev = zlib.crc32(eachLine,prev)
return%X%(prev& 0xFFFFFFFF)
PS2:由于评论中的建议,旧PS已被弃用 - 因此被删除。谢谢。我不明白,我是如何错过这个的,但它确实很好。
I want to calculate the CRC of file and get output like: E45A12AC
. Here's my code:
#!/usr/bin/env python
import os, sys
import zlib
def crc(fileName):
fd = open(fileName,"rb")
content = fd.readlines()
fd.close()
for eachLine in content:
zlib.crc32(eachLine)
for eachFile in sys.argv[1:]:
crc(eachFile)
This calculates the CRC for each line, but its output (e.g. -1767935985
) is not what I want.
Hashlib works the way I want, but it computes the md5:
import hashlib
m = hashlib.md5()
for line in open('data.txt', 'rb'):
m.update(line)
print m.hexdigest()
Is it possible to get something similar using zlib.crc32
?
A little more compact and optimized code
def crc(fileName):
prev = 0
for eachLine in open(fileName,"rb"):
prev = zlib.crc32(eachLine, prev)
return "%X"%(prev & 0xFFFFFFFF)
PS2: Old PS is deprecated - therefore deleted -, because of the suggestion in the comment. Thank you. I don't get, how I missed this, but it was really good.
这篇关于在python中计算文件的crc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!