Skip to content

Instantly share code, notes, and snippets.

@shyuep
Last active December 13, 2015 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shyuep/d4b87e665379b5b9b670 to your computer and use it in GitHub Desktop.
Save shyuep/d4b87e665379b5b9b670 to your computer and use it in GitHub Desktop.
Clean Google Drive
#!/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