尝试在python中获取最新创建的目录时出错
我想获取最新创建的目录。我跟着这个post。但是当我尝试它时会出现错误。尝试在python中获取最新创建的目录时出错
这里是我的目录列表
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
我想获得最新创建的文件以“DIFF”
开始这里是我试过了。
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()
当我运行该脚本,我得到
./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
我做了上述
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]
在功能上的微小变化,现在我得到:
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'
这确实因为我直接看到这一点,所以没有意义ory'FULL-2016-01-14_14-11'当我执行ls
命令。
我做错了什么。我无法弄清楚。
感谢
您需要完整的路径名称,这样只需将其添加到d列表理解
def get_latest_directory():
path_to_backups = 'path/to/backups/'
all_dirs = [path_to_backsups + d for d in os.listdir(path_to_backups) if (os.path.isdir(path_to_backups + 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()
它对'all_dirs = [d for os.listdir('backups')if(os.path.isdir(d)and d.startswith('DIFF'))]' –
我给+1了。有人downvoted –
@brainstorm对不起,我原来的答案我认为你已经修复了你的列表理解,但看着它更接近我意识到你仍然错过了完整的路径。这会导致'os.path.isdir(d)'失败,这会导致'all_dirs'为空 – SirParselot
由于SirParselot介绍,你需要完整的路径,而os.listdir()
只是给你的相对路径。要解决此问题,请使用os.path.abspath()
,它将相对路径映射到绝对路径。
[os.path.abspath(d) for d in os.listdir('backups') if (...)]
'os.path.abspath(d)'会给你所在的目录的完整路径不一定是你想要的路径 – SirParselot
我的猜测是你需要完整的路径名。 'listdir'没有给出完整路径 – SirParselot
你需要''.path.join',但我不知道你为什么不使用glob,因为它也在链接问题中使用 –