2

I have two directory with .xlsb and .msg extension i.e. for monthly and weekly. I want to get the most recent file from each folder.

I am using the same code for both, but I am getting error only for weekly folder.

self.weekly_file = [os.path.join(self.weekly_path, x) for x in os.listdir(self.weekly_path) if
                          x.endswith(".xlsb")]
    
print(self.weekly_file)
self.newest_weekly_file = os.path.basename(max(self.weekly_file, key=os.path.getctime))
print(self.newest_weekly_file)

I am getting error as:

return os.stat(filename).st_ctime
OSError: [WinError 1] Incorrect function: '\\\\docs.xyz.net.au\\sites\\K7777\\Reports\\Week\\Week - 2021-05-10.xlsb'

Even I tried the below code, this is giving only the folder name.

self.weekly_file = glob.glob(self.weekly_path)
desertnaut
  • 57,590
  • 26
  • 140
  • 166
KKL
  • 41
  • 2
  • 1
    can you try to sort the files by modification date? – rok Aug 03 '21 at 09:40
  • @rock Can you please help me how can I do that, I am new to Python. – KKL Aug 03 '21 at 10:09
  • Looks like your files are not local which might be a problem. Your files seem to have timestamps. If you can rely on them then just use `max` without a `key`-function? – Timus Aug 03 '21 at 10:31
  • which line give raise to the error? have you isolated it? Your strategy seems good, guess joining the paths could be the problem – cards Aug 03 '21 at 15:03
  • @Timus Thanks , It solved my problem, just wanted to know if it can be reliable because every week 1 file will be added and I have to pick the latest one and process it. – KKL Aug 03 '21 at 15:34
  • @cards, There is no problem with joining the path, I am getting the correct files in list. – KKL Aug 03 '21 at 15:35

1 Answers1

1

Try this instead:

xlsb_weekly = glob.glob('self.weekly_path/*.xlsb')
newest_weekly_file = max(xlsb_weekly, key=os.path.getctime)
print(newest_weekly_file)
Meriem
  • 130
  • 10