Python - 使用子目录从文件夹复制最新文件

时间:2017-05-15 20:10:19

标签: python python-2.7

我试图从一系列文件夹中复制最新文件。这是结构:

\\主机\数据\ folder1中\ *。BK

\\主机\数据\文件夹2 \ *。BK

\\主机\数据\ folder3 \ *。BK

\\主机\数据\ folder4 \ *。BK

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

我完全迷失在这里并尝试了许多没有运气的事情。这应该很简单,我不确定为什么我会遇到这么大的问题。

基本代码,

Header always set Strict-Transport-Security "max-age=31536000; 
includeSubDomains; preload" env=HTTPS

1 个答案:

答案 0 :(得分:1)

我在文本编辑器中写了以下内容,所以我无法对其进行全面测试;但这应该可以让你在那里大部分时间。

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)
相关问题