Skip to main content
 首页 » 编程设计

python文件操作

2025年05月04日18落叶无声

请问,这行是什么意思:

return [f[:f.rindex(".")] for f in os.listdir(path) if f and len(f) >= 4 and f[-2:]  
 
== "py" and f[-1] != "o" and f[-1] != "c"] 

我在这个链接的脚本中找到了它:

http://www-users.cs.umn.edu/~mein/blender/plugins/python/misc/scriptloader/TheOneScript.py

我知道我需要将文件名与其扩展名 (.py) 分开......但为什么 len(f)>=4

f[-1] != "o"或 "c".. 这是什么意思?

请您参考如下方法:

长度检查是因为最短的合理文件名是单个字符后跟 .py,它至少有 4 个字符。

最后的检查似乎是试图合并扩展名为 .pyc 和 .pyo 的编译文件,但这完全没有必要,因为它们不符合条件 f[-2:] == "py".

要将文件名拆分为根目录和扩展名,您还可以考虑使用 os.path.splitext .

[root for (root, ext) in map(os.path.splitext, os.listdir(path)) if ext == '.py']