Reputation: 824
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).
Unprocessed subdirectory
Processed subdirectory
Example of processed folder (after running the process that empties the unprocessed directory and moves the files here.
Upvotes: 1
Views: 165
Reputation: 2085
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'
try:
filesToMove = os.listdir(UNPROCESSED_PATH)
except FileNotFoundError:
print(f"No '{UNPROCESSED_PATH}' directory found")
exit()
if len(filesToMove) == 0:
print('No files to process')
exit()
currTime = datetime.datetime.now()
currTimeStr = currTime.strftime("%d%m%y_%H%M%S")
newDirPath = f'{PROCESSED_PATH}/Pr_{currTimeStr}'
os.mkdir(newDirPath)
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
.
Upvotes: 1