Skip to content

Instantly share code, notes, and snippets.

@beall49
Last active January 1, 2020 20:50
Show Gist options
  • Save beall49/f321299953f0ae413376e5f2096a403c to your computer and use it in GitHub Desktop.
Save beall49/f321299953f0ae413376e5f2096a403c to your computer and use it in GitHub Desktop.
recursively walk directories and move files to a single output directory
import glob
import os
import shutil
import datetime
import random
import string
FILE_DIR = "P:\\original\\"
OUTPUT_DIR = "P:\\destination\\"
files = []
def get_random_string(string_len=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(string_len))
suffix_list = []
for root, d, file_list in os.walk(FILE_DIR):
for file in file_list:
files.append(os.path.join(root, file))
error_files = []
for file in files:
fn, suffix = os.path.splitext(file)
file_path, file_name = os.path.split(os.path.abspath(file))
random_string = get_random_string()
cleaned_file_name = file_name.replace(" ", '.').replace(suffix, '')
# inserting random string in case some files have the same name from different directories
dest = "{}\\{}.{}{}".format(file_path, cleaned_file_name, random_string, suffix)
try:
os.rename(file, dest)
shutil.move(dest, OUTPUT_DIR)
except:
error_files.append(file)
#print out any files that didn't get moved
print('\n'.join(error_files))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment