Python: “OSError: [Errno 2] No such file or directory:”… with the file it found?

前端 未结 1 703
春和景丽
春和景丽 2021-01-26 10:05

I\'m writing a Python script where part of its function is to find the last modified file of a specific kind. In my case, it\'s for the last modified screen saver plist file on

相关标签:
1条回答
  • 2021-01-26 10:24

    listdir won't prepend the directory name, so you cannot pass os.path.getmtime as-is.

    Wrap it with a lambda and join with the source directory:

    MacPlistFile = max((f for f in os.listdir(MacPlistPath) if f.lower().endswith('.plist') and f.lower().startswith('com.apple.screensaver.')), key=lambda f : os.path.getmtime(os.path.join(MacPlistPath,f)))
    

    But looking at the bigger picture, you'd be even better off with glob.glob and a wildcard:

    import glob
    MacPlistFile = os.path.basename(max(glob.glob(os.path.join(MacPlistPath,"com.apple.screensaver.*.plist")), key=os.path.getmtime))
    

    glob.glob returns the full path, so now you can use os.path.getmtime directly as a key. You just have to perform an os.path.basename in the end to get only the last modified file name.

    Aside: no need to create a list comprehension. A generator comprehension is enough for max to work efficiently.

    0 讨论(0)
提交回复
热议问题