Skip to content

Instantly share code, notes, and snippets.

@blha303
Last active December 3, 2022 21:04
Show Gist options
  • Save blha303/3ddb83da7a4d8ecc93b3f1432baefe61 to your computer and use it in GitHub Desktop.
Save blha303/3ddb83da7a4d8ecc93b3f1432baefe61 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import zlib
import os
import sys
import argparse
def crc32_file(filename):
with open(filename, "rb") as f:
return hex(zlib.crc32(f.read())).upper()[2:].zfill(8)
def get_files_recursively(directory="."):
for root, dirs, files in os.walk(os.path.abspath(directory)):
for name in files:
yield os.path.join(root, name)
def add_crc_to_fn(filename):
new_name = "{0} [{2}]{1}".format(*os.path.splitext(filename), crc32_file(filename))
try:
os.rename(filename, new_name)
print("{} >> {}".format(filename, new_name), file=sys.stderr)
except (OSError, IOError) as e:
print("{} Unable to rename {}".format(e.__class__.__name__, filename))
def add_crc_to_sfv(filename):
crc = crc32_file(filename)
dirname = os.path.dirname(filename)
line = "{} {}\n".format(os.path.basename(filename), crc)
sfv_path = os.path.join(dirname, os.path.basename(dirname) + ".sfv")
try:
with open(sfv_path, "a") as f:
f.write(line)
print("{} >> {}".format(filename, crc))
except (OSError, IOError) as e:
print("{} Unable to create {}".format(e.__class__.__name__, sfv_path))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--directory", default=".")
parser.add_argument("--filename", help="Writes checksum into filename", action="store_true")
args = parser.parse_args()
for filename in get_files_recursively(directory=args.directory):
if args.filename:
add_crc_to_fn(filename)
else:
add_crc_to_sfv(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment