Python move all files in directory to sub-directory with timestamp in another directory

I have a directory (Unprocessed) in which I have some files. I need a python way to create a timestamped sub-directory (Pr_DDMMYY_HHMiSS) in another directory (Processed) and move the mentioned files inside that newly created sub-directory (Pr_DDMMYY_HHMiSS). Those to-be-created sub-directories will act as backups for the changes in the files. Other solution designs are also welcome.

Main directory (unprocessed would host the to-be-processed files and, when processed, those would be moved to processed, in Pr_150321_195708 (Pr_DDMMYY_HHMiSS).

enter image description here

Unprocessed subdirectory

enter image description here

Processed subdirectory

enter image description here

Example of processed folder (after running the process that empties the unprocessed directory and moves the files here.

enter image description here


Assuming your script is on the same folder as Processed and Unprocessed directories, you could do this:

import os, shutil, datetime

UNPROCESSED_PATH = 'Unprocessed'
PROCESSED_PATH = 'Processed'

    filesToMove = os.listdir(UNPROCESSED_PATH)
except FileNotFoundError:
    print(f"No '{UNPROCESSED_PATH}' directory found")

if len(filesToMove) == 0:
    print('No files to process')

currTime =
currTimeStr = currTime.strftime("%d%m%y_%H%M%S")

newDirPath = f'{PROCESSED_PATH}/Pr_{currTimeStr}'
print(f'Created {newDirPath} directory')

for file in filesToMove:
    shutil.move(f'{UNPROCESSED_PATH}/{file}', f'{newDirPath}/{file}')
    print(f'Moving {file}')

print(f'Done processing {len(filesToMove)} files')

Tested with Python 3.6.4 on a Windows Pro.

Leave a Reply

Your email address will not be published. Required fields are marked *