I want to get the newest created directory. I followed this post. but I get errors when I tried it.
Here is my directory listing
ls backups
BACKUPSET_2016-01-14_11-26_.zip DIFF-2016-01-17_00-00 DIFF-2016-01-20_00-00
BACKUPSET_2016-01-14_11-28_.zip DIFF-2016-01-18_00-00 DIFF-2016-01-21_00-00
DIFF-2016-01-16_00-00 DIFF-2016-01-19_00-00 FULL-2016-01-14_14-11
I want to get the newest created file that starts with "DIFF"
Here is what I tried.
def get_latest_directory():
all_dirs = [d for d in os.listdir('backups') if (os.path.isdir(d) and d.startswith('DIFF'))]
print sorted(all_dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]
if __name__=="__main__":
get_latest_directory()
when I run this script, I get
./backup.py
Traceback (most recent call last):
File "./backup.py", line 33, in <module>
get_latest_directory()
File "./backup.py", line 19, in get_latest_directory
print sorted(all_dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]
IndexError: list index out of range
I made a small change in function above
def get_latest_directory():
all_dirs = [d for d in os.listdir('backups')]
print sorted(all_dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]
now I get:
Traceback (most recent call last):
File "./backup.py", line 34, in <module>
get_latest_directory()
File "./backup.py", line 20, in get_latest_directory
print sorted(all_dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]
File "./backup.py", line 20, in <lambda>
print sorted(all_dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]
File "/usr/lib64/python2.7/genericpath.py", line 64, in getctime
return os.stat(filename).st_ctime
OSError: [Errno 2] No such file or directory: 'FULL-2016-01-14_14-11'
This does not make sense since I see this directory 'FULL-2016-01-14_14-11' when i execute the ls
command.
what I am doing wrong. I am unable to figure out.
Thanks