我在 Windows 上运行 Python 3.5.1。我试图通过计算它们的哈希值在目录中找到重复的源代码文件。问题是 Python 似乎认为某些文件是空的。这是相关的代码片段:
with open(path, 'rb') as afile:
hasher = hashlib.md5()
data = afile.read()
hasher.update(data)
print("len(data): {}, Path: {}, Hash:{}".format(len(data), path, hasher.hexdigest()))
这是一些示例输出:
len(data): 0, Path: h:\t\TCPServerSocket.h, Hash:d41d8cd98f00b204e9800998ecf8427e
len(data): 0, Path: h:\t\TCPSocket.cpp, Hash:d41d8cd98f00b204e9800998ecf8427e
len(data): 0, Path: h:\t\TCPSocket.h, Hash:d41d8cd98f00b204e9800998ecf8427e
len(data): 5073, Path: h:\t\ConfigFile.cpp, Hash:6188d6a0e0bc02edf27ce232689beff6
我向您保证这些文件不是空的,并且 Python 在执行过程中不会抛出任何错误。有什么想法吗?
请您参考如下方法:
如果不是这种情况,我将删除此答案,但这是您需要检查的内容。把它直接放在 open block 之前
print("the path is {!r}".format(path))
print("path exists: ", os.path.exists(path))
print("it is a file: ", os.path.isfile(path))
print("file size is: ", os.path.getsize(path))
因为输出中的所有内容都与该文件实际上是空的一致。所以也许是?我的第一个想法是您可能会在其他地方清零文件,尽管您很快就会发现这一点。
