Python:"OSError:[Errno 2]没有此类文件或目录:" ...找到的文件? [英] Python: "OSError: [Errno 2] No such file or directory:"... with the file it found?
问题描述
我正在编写一个Python脚本,其部分功能是查找特定种类的最后修改文件.就我而言,它是用于Mac OS X上最后修改的屏幕保护程序plist文件.下面是处理此问题的一些代码:
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 Mac OS X. Below are the bits of code which deal with this:
import os
PlistFolder = "Library/Preferences/ByHost"
MacPlistPath = os.path.join(HomeFolder, PlistFolder)
PlistSSMac = max([f for f in os.listdir(MacPlistPath) if f.lower().endswith('.plist') and f.lower().startswith('com.apple.screensaver.')], key=os.path.getmtime)
但是,当我运行它时,它在返回所需的确切信息时给了我一个错误...
When I run it, however, it gives me an error while returning exactly what I wanted it to find...
Traceback (most recent call last):
File "tcn_test.py", line 29, in <module>
MacPlistFile = max([f for f in os.listdir(MacPlistPath) if f.lower().endswith('.plist') and f.lower().startswith('com.apple.screensave
r.')], key=os.path.getmtime)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 62, in getmtime
return os.stat(filename).st_mtime
OSError: [Errno 2] No such file or directory: 'com.apple.screensaver.097EBF05-D7B5-5FD6-A031-12734A82135D.plist'
关于导致此问题的原因以及如何解决的任何想法?
Any ideas on what causes this and how I can fix it?
提前谢谢!
推荐答案
listdir
不会在目录名前添加,因此您不能原样传递os.path.getmtime
.
listdir
won't prepend the directory name, so you cannot pass os.path.getmtime
as-is.
用lambda包裹起来,并与源目录连接:
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)))
但是,从更大的角度来看,使用glob.glob
和通配符会更好:
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
返回完整路径,因此现在您可以直接将os.path.getmtime
用作键.您只需要在最后执行os.path.basename
即可仅获取最后修改的文件名.
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.
此外:无需创建列表理解. 生成器理解足以使max
有效地工作.
Aside: no need to create a list comprehension. A generator comprehension is enough for max
to work efficiently.
这篇关于Python:"OSError:[Errno 2]没有此类文件或目录:" ...找到的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!