benipy
benipy

Reputation: 111

glob.iglob Remove path from filename

I am trying to get the most recent file added to a directory using python 2.7 os and glob modules.

import os
import glob

path = "files/"
newestFile = max(glob.iglob(path + '*.txt'), key=os.path.getctime)

print newestFile

When I print the newestFile variable I get the path included i.e.

files\file.txt

I just want the filename but my .txt file and .py script are not in the same directory. The text file is one directory down under the files directory. How do I refer to the directory and get the newest .txt file added to that directory.

Upvotes: 2

Views: 6437

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180482

You can use os.path.basename to just get the filename:

newestFile = os.path.basename(max(glob.iglob(path + '*.txt'), key=os.path.getctime))

os.path.getctime is going to need the full path so one way or another you would have to use the full path.

Upvotes: 2

Related Questions