简体   繁体   中英

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).

在此处输入图像描述

Unprocessed subdirectory

在此处输入图像描述

Processed subdirectory

在此处输入图像描述

Example of processed folder (after running the process that empties the unprocessed directory and moves the files 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'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM