-3
import glob
import os

list_of_files = glob.glob('/path/to/folder/*')
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

This code prints the file path as well, which is not required. I just need the latest file name.

martineau
  • 119,623
  • 25
  • 170
  • 301
Zaved Ali
  • 7
  • 2
  • Does this answer your question? [Separate file name from path](https://stackoverflow.com/questions/23235915/separate-file-name-from-path) – zvone Dec 08 '20 at 07:58
  • 1
    Does this answer your question? [Extract file name from path, no matter what the os/path format](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format) – Tomerikoo Dec 08 '20 at 08:59

2 Answers2

0

Try os.path.basename(latest_file), see os:

import glob
import os

list_of_files = glob.glob('/path/to/folder/*')
latest_file = max(list_of_files, key=os.path.getctime)
print(os.path.basename(latest_file))

Get's you foo.bar

Albo
  • 1,584
  • 9
  • 27
0
list_of_files = '//x.x.x./y$/Process/Daily_Mismatch_Report/'

def get_latest_file(path, *paths): """Returns the name of the latest (most recent) file of the joined path(s)""" fullpath = os.path.join(path, paths) files = glob.glob(fullpath) if not files: return None latest_file = max(files, key=os.path.getctime) filename = os.path.split(latest_file) return filename p,f= get_latest_file(list_of_files,'.txt') print(f)

Zaved Ali
  • 7
  • 2