Python:"OSError:[Errno 2]没有此类文件或目录:" ...找到的文件?

编程入门 行业动态 更新时间:2024-10-25 17:23:01
本文介绍了Python:"OSError:[Errno 2]没有此类文件或目录:" ...找到的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个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]没有此类文件或目录:" ...找到的文件?

本文发布于:2023-07-04 11:10:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   此类   目录   quot   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!