【问题标题】:Python - Copying Most Recent File From Folder with SubDirectoriesPython - 从带有子目录的文件夹中复制最新文件
【发布时间】:2017-05-15 20:10:19
【问题描述】:

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

\\host\data\folder1\*.bk

\\host\data\folder2\*.bk

\\host\data\folder3\*.bk

\\host\data\folder4\*.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 + "\\"

【问题讨论】:

  • 在工作的时候,我可以组合的模拟代码是有限的,但不久前我写了一些类似的东西。欢迎您获取代码并玩转:github.com/DavidMetcalfe/…
  • 这是一个不错的脚本,但对我来说效果不佳。有时那里有从今天开始的文件,有时是一周前的文件,等等。所以我只想获取最新的文件,无论日期如何。
  • 由于您将寻找mtime,这可能对最近的有帮助,因为我在提供的脚本中选择了最旧的。 stackoverflow.com/a/2014704/563231

标签: python python-2.7


【解决方案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)

【讨论】:

  • @HMan06 没问题,乐于助人!
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 2017-09-16
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多