Search code examples
python-2.7datetimesmb

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


On my network, a scheduled report creates a new directory (with random numbers) every time it runs and then places a CSV file inside it. I currently fetch files over SMB using pysmbclient, but I'm not sure how I can navigate to this reports latest directory with what the modules Glob returns (below).

How can I get to the last created directory, do I need to parse the datetime.datetime's first somehow? Here's what I have:

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))]


Solution

  • Those 4-tuples are how 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
    

    And then you would use os.path.join to build up the path to download:

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