使用datetime从列表中的元组中查找最新目录

时间:2017-04-25 21:42:49

标签: python-2.7 datetime smb

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

如何进入上一个创建的目录,是否需要首先以某种方式解析 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))]

1 个答案:

答案 0 :(得分:2)

这些4元组是pysmbclientsmb.glob()返回数据的方式。您不需要解析日期时间,因为它们已经是datetime.datetime个对象,可以按照您通常排序的方式进行排序。要获得每个4元组的最终(第3个)值,您可以使用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")