Python从包含子目录的文件夹复制最新文件

2024-04-27 00:08:16 发布

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

我正试图从一系列文件夹中复制最新的文件。结构如下:

\\主机\数据\文件夹1\*.bk

\\主机\数据\文件夹2\*.bk

\\主机\数据\文件夹3\*.bk

\\主机\数据\文件夹4\*.bk

大约有600个这样的文件夹。我想把最新的文件从每个文件夹复制到一个文件夹中。有些文件夹也可能是空的。在

我在这里完全迷路了,尝试了很多没有运气的事情。这应该很容易,我不知道为什么我会有这么大的问题。在

基本代码

import os, shutil, sys

source = r"\\server\data"
dest = r"e:\dest"

for pth in os.listdir(source):
    if "." not in pth:
        newsource = source + "\\" + pth + "\\"

Tags: 文件数据in文件夹sourceos事情结构
1条回答
网友
1楼 · 发布于 2024-04-27 00:08:16

我在下面写了一篇文章,但我不能完全写下这篇文章。在

import os
import operator

source = r"\\server\data"
destination = r"e:\dest"

time_dict = {}

#Walk all of the sub directories of 'data'
for subdir, dirs, files in os.walk(source):
    #put each file into a dictionary with thier creation time
    for file in os.listdir(dir):
        time = os.path.getctime(os.path.join(subdir,file))
        time_dict.update({time,file})
    #sort the dict by time
    sorted_dict = sorted(time_dict.items(), key=operator.itemgetter(0))
    #find the most recent
    most_recent_file = next(iter(sorted_dict))
    #move the most recent file to the destination directory following the source folder structure
    os.rename(source + '\\' + dir + '\\' + most_recent_file,str(destination) + '\\' + dir + '\\' + most_recent_file)

相关问题 更多 >