VS = hashlib.md5()
如何为for循环中的每个文件创建新哈希?
import os
import hashlib
VS = hashlib.md5()
rootDir = r"C:\Users\Ghost\Pictures\Wallpaper"
for dirName, subdirList, fileList in os.walk(rootDir, topdown=True):
print('Directory:', dirName)
for x in fileList:
print('Filename: ' , x, '\t', VS.hexdigest())
输出:
Directory: C:\Users\Ghost\Pictures\Wallpaper
Filename: 0020.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: 2215.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: 55845.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: anon.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: Eyes_HD.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: gow.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: kk.png d41d8cd98f00b204e9800998ecf8427e
Filename: scanEQ.txt d41d8cd98f00b204e9800998ecf8427e
Filename: scanEQQ.txt d41d8cd98f00b204e9800998ecf8427e
Filename: scooby.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: skull.jpg d41d8cd98f00b204e9800998ecf8427e
Filename: sniper.jpg d41d8cd98f00b204e9800998ecf8427e
答案 0 :(得分:1)
我想我有一个这样的目录:
test
├── callfoo.py
├── folder
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ └── submodule.cpython-35.pyc
│ └── submodule.py
└── inherit.py
2 directories, 6 files
您可以这样做:
import os
import hashlib
def md5_checksum(path, size=1024):
VS = hashlib.md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(size), b''):
VS.update(chunk)
return VS.hexdigest()
rootDir = r"/home/nexus/Bureau/stack/test"
size = 1024
for dirName, subdirList, fileList in os.walk(rootDir, topdown=True):
for _file in fileList:
path = dirName + '/' + _file
checksum = md5_checksum(path, size)
print('File: {0} \t {1}'.format(_file, checksum))
输出:
File: callfoo.py 52cf7effa72135d50d8389bc81c73672
File: inherit.py 919a85d8976d67eea97562a4f8a7e2b9
File: submodule.py 3be5b4123199df6a01b368f2f343821c
File: __init__.py d41d8cd98f00b204e9800998ecf8427e
File: __init__.cpython-35.pyc 2e4511c482f711fe68bdc825ce658375
File: submodule.cpython-35.pyc f93d319156617e2cfca3cee88edfcc2a
答案 1 :(得分:1)
在调用之前添加
sharedPreference
VS.update(b"new values")
就够了:
VS.hexdigest()
输出:
import os
import hashlib
VS = hashlib.md5()
rootDir = r"C:\Users\Ghost\Pictures\Wallpaper"
for dirName, subdirList, fileList in os.walk(rootDir, topdown=True):
print('Directory:', dirName)
for x in fileList:
VS.update(b"new values")
print('Filename: ' , x, '\t', VS.hexdigest())