File size: 1,597 Bytes
180cdb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import hashlib
import os

def calculate_sha1(file_path):
    sha1 = hashlib.sha1()
    with open(file_path, 'rb') as file:
        while True:
            data = file.read(8192)  # 8KB chunks
            if not data:
                break
            sha1.update(data)
    return sha1.hexdigest().upper()

def find_files_and_calculate_sha1():
    current_directory = os.getcwd()
    output_file = os.path.abspath("sha1_hashes.txt")

    count = 0
    skipped = 0

    with open(output_file, 'w', encoding='utf-8', newline='\n') as out_file:
        # onerror prevents the whole walk from dying on permission errors
        for root, dirs, files in os.walk(current_directory, topdown=True, onerror=lambda e: print(f"! Skipping dir: {e}")):
            for name in files:
                file_path = os.path.join(root, name)
                # Don't hash the output file while we're writing to it
                if os.path.abspath(file_path) == output_file:
                    continue
                rel = os.path.relpath(file_path, start=current_directory)
                try:
                    sha1_hash = calculate_sha1(file_path)
                except Exception as e:
                    print(f"! Skipping {rel} - {e}")
                    skipped += 1
                    continue
                out_file.write(f"{rel}\t{sha1_hash}\n")
                count += 1
                print(f"{count}. Processing: {rel}")

    print(f"SHA1 hashes written to {output_file}. Hashed {count} file(s), skipped {skipped}.")

# Run it
if __name__ == "__main__":
    find_files_and_calculate_sha1()