Last active
December 13, 2015 21:38
-
-
Save shyuep/d4b87e665379b5b9b670 to your computer and use it in GitHub Desktop.
Clean Google Drive
This file contains 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 python | |
import os | |
import glob | |
import re | |
import shutil | |
import filecmp | |
""" | |
Simple script for cleaning Google Drive of bad renames (e.g., add " (1)" to file or folder names) | |
and duplicates. | |
""" | |
def main(args): | |
p = re.compile("(.*) \((\d+)\)(\.\w+)" if not args.dir_mode else "(.*) \((\d+)\)()") | |
to_rn = [] | |
to_remove = [] | |
print("The following files are to be renamed.") | |
for parent, folders, files in os.walk(args.groot): | |
to_process = folders if args.dir_mode else files | |
for f in to_process: | |
m = p.match(f) | |
if m: | |
if len(m.group(2)) < 3: | |
src = os.path.join(parent, f) | |
dest = os.path.join(parent, m.group(1) + m.group(3)) | |
if not os.path.exists(dest): | |
print(src) | |
to_rn.append((src, dest)) | |
else: | |
if filecmp.cmp(src, dest): | |
to_remove.append((src, dest)) | |
else: | |
print("%s exists!" % dest) | |
if len(to_rn) > 0: | |
if args.force: | |
r = "y" | |
else: | |
r = raw_input("Rename %d files? (y/n) " % len(to_rn)) | |
if r == "y": | |
for src, dest in to_rn: | |
print("Renaming %s -> %s" % (src, dest)) | |
shutil.move(src, dest) | |
else: | |
print("No files to rename!") | |
print("") | |
print("%d duplicates!" % len(to_remove)) | |
for src, dest in to_remove: | |
if args.force: | |
r = "y" | |
else: | |
r = raw_input("%s seems to be the same as %s. Delete %s? (y/n) " % (dest, src, src)) | |
if r == "y": | |
os.remove(src) | |
if __name__ == "__main__": | |
import argparse | |
p = argparse.ArgumentParser(description="Clean renames and dupes from Google Drive.") | |
p.add_argument("-f", "--force", | |
dest="force", action="store_true", | |
help="If true, no confirmation will be asked for removal.") | |
p.add_argument("-d", "--dir", | |
dest="dir_mode", action="store_true", | |
help="If True, then directories will be processed. Otherwise, files will be processed.") | |
p.add_argument("-g", "--groot", dest="groot", type=str, nargs="?", | |
default=os.path.join(os.environ["HOME"], "Google Drive"), | |
help="Set root directory where Google Drive resides. Defaults to $HOME/Google Drive") | |
p.set_defaults(func=main) | |
args = p.parse_args() | |
try: | |
a = getattr(args, "func") | |
except AttributeError: | |
p.print_help() | |
sys.exit(0) | |
args.func(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment