You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importhashlibimportosdefget_md5(file_path):
"""Generates the MD5 hash of a file in chunks to save memory."""hash_md5=hashlib.md5()
withopen(file_path, "rb") asf:
# Read in 4KB chunksforchunkiniter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
returnhash_md5.hexdigest()
defrename_to_md5(directory):
# Supported extensionsextensions= ('.jpg', '.jpeg', '.png', '.mp4')
forfilenameinos.listdir(directory):
iffilename.lower().endswith(extensions):
file_path=os.path.join(directory, filename)
# Skip if it's a directoryifos.path.isdir(file_path):
continuefile_ext=os.path.splitext(filename)[1]
new_hash=get_md5(file_path)
new_name=f"{new_hash}{file_ext}"new_path=os.path.join(directory, new_name)
# Rename if the name isn't already the hashiffilename!=new_name:
try:
os.rename(file_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
exceptFileExistsError:
print(f"Skipped: {new_name} already exists (Duplicate file).")
# Run the script in the current directoryif__name__=="__main__":
target_dir="."# Change this to your folder pathrename_to_md5(target_dir)