简体   繁体   English

Python 将目录中的所有文件移动到另一个目录中带有时间戳的子目录

[英]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).我需要一种 python 方式在另一个目录(已处理)中创建一个带时间戳的子目录(Pr_DDMMYY_HHMiSS),并将上述文件移动到新创建的子目录(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).主目录(未处理的将托管待处理的文件,并且在处理时,这些文件将移动到已处理的 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:假设您的脚本与ProcessedUnprocessed目录位于同一文件夹中,您可以这样做:

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 .Windows Pro上使用Python 3.6.4进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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