Created
May 4, 2018 17:06
-
-
Save icedraco/a15303c95d685267e96eb18133555dcb to your computer and use it in GitHub Desktop.
Re-encode broken filenames from Google Drive Takeout folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
from typing import List, Callable | |
def transform(name: str) -> str: | |
return bytes(name, "latin1").decode("utf-8") | |
def rename_all(root: str, orig_names: List[str], transform: Callable[[str], str], test=False) -> int : | |
name_pairs = ((n, transform(n)) for n in orig_names) | |
filtered_names = [e for e in name_pairs if e[0] != e[1]] | |
for orig, dst in filtered_names: | |
orig_path = os.path.join(root, orig) | |
dst_path = os.path.join(root, dst) | |
print("{}: {} -> {}".format(root, orig, dst)) | |
if not test: | |
os.rename(orig_path, dst_path) | |
return len(filtered_names) | |
def main(path: str, is_test: bool = False) -> int: | |
old_path = os.getcwd() | |
os.chdir(path) | |
dirs_renamed = 0 | |
dirs_total = 0 | |
files_renamed = 0 | |
files_total = 0 | |
for root, dirnames, filenames in os.walk(".", topdown=False): | |
print("--> {}".format(root)) | |
dirs_total += len(dirnames) | |
files_total += len(filenames) | |
dirs_renamed += rename_all(root, dirnames, transform, is_test) | |
files_renamed += rename_all(root, filenames, transform, is_test) | |
print() | |
print("Dirs renamed: {}/{}".format(dirs_renamed, dirs_total)) | |
print("Files renamed: {}/{}".format(files_renamed, files_total)) | |
print("ALL DONE") | |
return 0 | |
if __name__ == "__main__": | |
from sys import argv | |
path = argv[1] if len(argv) >= 2 else "." | |
raise SystemExit(main(path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment