Python-从包含子目录的文件夹复制最新文件
我正在尝试从一系列文件夹中复制最新的文件。结构如下: \\主机\数据\文件夹1\*.bk \\主机\数据\文件夹2\*.bk \\主机\数据\文件夹3\*.bk \\主机\数据\文件夹4\*.bk 其中大约有600个文件夹。我想将每个文件夹中最近的文件复制到单个文件夹中。有些文件夹也可能是空的 我在这里完全迷路了,尝试了很多事情却没有成功。这应该很容易,我不知道为什么我有这么大的问题 基本准则Python-从包含子目录的文件夹复制最新文件,python,python-2.7,Python,Python 2.7,我正在尝试从一系列文件夹中复制最新的文件。结构如下: \\主机\数据\文件夹1\*.bk \\主机\数据\文件夹2\*.bk \\主机\数据\文件夹3\*.bk \\主机\数据\文件夹4\*.bk 其中大约有600个文件夹。我想将每个文件夹中最近的文件复制到单个文件夹中。有些文件夹也可能是空的 我在这里完全迷路了,尝试了很多事情却没有成功。这应该很容易,我不知道为什么我有这么大的问题 基本准则 import os, shutil, sys source = r"\\server\data" d
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 + "\\"
我在一个文本编辑器中写了下面的内容,所以我无法完全测试它;但这应该能让你走到那里
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)
在我工作的时候,我的模拟代码有限,但不久前我写了一些类似的东西。欢迎您抓取代码并四处玩:这是一个很好的脚本,但对我来说不会很好。有时那里有今天的文件,有时是一周前的文件,等等。所以我只想获取最新的文件,不管日期如何。因为您将查找
mtime
,这可能对最近的文件有所帮助,因为我在提供的脚本中查找了最旧的文件@没问题,很乐意帮忙!