Last active 1670065451

checksummer.py Raw
1#!/usr/bin/env python3
2import zlib
3import os
4import sys
5import argparse
6
7def crc32_file(filename):
8 with open(filename, "rb") as f:
9 return hex(zlib.crc32(f.read())).upper()[2:].zfill(8)
10
11def get_files_recursively(directory="."):
12 for root, dirs, files in os.walk(os.path.abspath(directory)):
13 for name in files:
14 yield os.path.join(root, name)
15
16def add_crc_to_fn(filename):
17 new_name = "{0} [{2}]{1}".format(*os.path.splitext(filename), crc32_file(filename))
18 try:
19 os.rename(filename, new_name)
20 print("{} >> {}".format(filename, new_name), file=sys.stderr)
21 except (OSError, IOError) as e:
22 print("{} Unable to rename {}".format(e.__class__.__name__, filename))
23
24def add_crc_to_sfv(filename):
25 crc = crc32_file(filename)
26 dirname = os.path.dirname(filename)
27 line = "{} {}\n".format(os.path.basename(filename), crc)
28 sfv_path = os.path.join(dirname, os.path.basename(dirname) + ".sfv")
29 try:
30 with open(sfv_path, "a") as f:
31 f.write(line)
32 print("{} >> {}".format(filename, crc))
33 except (OSError, IOError) as e:
34 print("{} Unable to create {}".format(e.__class__.__name__, sfv_path))
35
36if __name__ == "__main__":
37 parser = argparse.ArgumentParser()
38 parser.add_argument("--directory", default=".")
39 parser.add_argument("--filename", help="Writes checksum into filename", action="store_true")
40 args = parser.parse_args()
41 for filename in get_files_recursively(directory=args.directory):
42 if args.filename:
43 add_crc_to_fn(filename)
44 else:
45 add_crc_to_sfv(filename)