Last active
January 1, 2020 20:50
-
-
Save beall49/f321299953f0ae413376e5f2096a403c to your computer and use it in GitHub Desktop.
recursively walk directories and move files to a single output directory
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
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