从带有日期时间的列表中的元组中查找最新目录

Find the newest directory from a tuple inside a list with datetime

在我的网络上,计划报告每次运行时都会创建一个新目录(带有随机数),然后在其中放置一个 CSV 文件。我目前使用 pysmbclient 通过 SMB 获取文件,但我不确定如何使用模块 Glob returns(如下)导航到此报告的最新目录。

我怎样才能到达最后创建的目录,我是否需要先以某种方式解析datetime.datetime?这是我拥有的:

import smbclient
import glob
import os

smb = smbclient.SambaClient(server=uk51, ip=10.10.10.10, share="share", 
      username="test", password="password", domain='office')

# recent = smb.glob(max(glob.iglob(\*)), key=os.path.getctime)) # Latest directory
# smb.download(recent + "summary.csv", "/usr/reports/uk51.csv")) # Download latest dir's CSV


example = smb.glob('\*')
print list(example) # Example of what Glob returns

#> python script.py

#> [(u'1192957', u'D', 0, datetime.datetime(2017, 4, 23, 10, 29, 20)), (u'1193044', u'D', 0, datetime.datetime(2017, 4, 24, 10, 29, 22))]

那些 4 元组是 pysmbclient returns data from smb.glob(). You don't need to parse the datetimes as they are already datetime.datetime objects which can be sorted as you would usually sort things. To get the final (3rd) value in each 4-tuple you can use operator.itemgetter:

import operator as op

#example = [(u'1193044', u'D', 0, datetime.datetime(2017, 4, 24, 10, 29, 22)), 
#           (u'1192957', u'D', 0, datetime.datetime(2017, 4, 23, 10, 29, 20))]
example = list(smb.glob('\*'))
example.sort(key=op.itemgetter(3),reverse=True)
most_recent_dir = example[0][0] # to get the most recent directory name

然后您将使用 os.path.join 建立下载路径:

import os

smb.download(os.path.join(most_recent_dir,"summary.csv"), "/usr/reports/uk51.csv")