python获取目录下所有文件的md5
时间: 2023-08-01 13:13:00 浏览: 52
你可以使用以下代码来获取目录下所有文件的MD5值:
```python
import hashlib
import os
def get_md5(file_path):
md5 = hashlib.md5()
with open(file_path, 'rb') as f:
while True:
data = f.read(4096)
if not data:
break
md5.update(data)
return md5.hexdigest()
def get_all_files_md5(directory):
file_md5 = {}
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
file_md5[file_path] = get_md5(file_path)
return file_md5
directory = "/path/to/directory"
md5_values = get_all_files_md5(directory)
for file_path, md5 in md5_values.items():
print(f"{file_path}: {md5}")
```
你需要将`/path/to/directory`替换为你要获取MD5值的目录路径。运行以上代码后,它将输出目录下每个文件的路径和对应的MD5值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)