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

2024-10-03 23:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录(未处理),其中有一些文件。 我需要一种python方法在另一个目录(已处理)中创建一个带时间戳的子目录(Pr_DDMMYY_HHMiSS),并将提到的文件移动到新创建的子目录(Pr_DDMMYY_HHMiSS)中。要创建的子目录将作为文件更改的备份。 也欢迎其他解决方案设计

主目录(未处理的将承载待处理的文件,处理后,这些文件将移动到Pr_150321_195708(Pr_DDMMYY_HHMiSS)中的已处理文件)

enter image description here

未处理的子目录

enter image description here

已处理子目录

enter image description here

已处理文件夹示例(在运行清空未处理目录并将文件移到此处的过程后)

enter image description here


Tags: 文件方法目录文件夹示例过程时间pr
1条回答
网友
1楼 · 发布于 2024-10-03 23:24:18

假设脚本与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')

Windows Pro上用Python 3.6.4测试

相关问题 更多 >