Files
Python/Collect a hash of all files in a directory/getHashes.py
T
2026-06-29 12:00:20 +03:00

31 lines
1.1 KiB
Python

import sys
import hashlib
from pathlib import Path
if len(sys.argv) > 1:
folder_path = Path(sys.argv[1])
else:
folder_path = Path(".") # Current directory
print(f"Check directory {folder_path}")
output_file = Path("hashes.txt")
with open(output_file, "w", encoding="utf-8") as f:
for file in folder_path.rglob("*"):
if file.is_file():
if file.is_symlink():
print(f"File is a link - {file}")
f.write(f"File is a link - {file}\n")
else:
hasher = hashlib.sha1()
try:
print(f"Getting a hash for a file: {file}")
# Read file in 64KB chunks to protect system memory
with open(file, "rb") as file_bytes:
for chunk in iter(lambda: file_bytes.read(65536), b""):
hasher.update(chunk)
file_hash = hasher.hexdigest()
f.write(f"{file_hash} - {file}\n")
except Exception as e:
f.write(f"ERROR {file} ({e})\n")