python文件操作
请问,这一行的含义是什么:
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" 呢..这是什么意思?
please, what is the meaning of this line:
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"]
I found it in a script in this link :
http://www-users.cs.umn.edu/~mein/blender/plugins/python/misc/scriptloader/TheOneScript.py
I know that i needed to split the file name from its extenstion (.py) .. but why len(f)>=4
and what about f[-1] != "o" or "c" .. what this is mean ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
长度检查是因为最短的合理文件名是一个字符后跟
.py
,它至少包含 4 个字符。最后的检查似乎试图忽略扩展名为
.pyc
和.pyo
的编译文件,但这完全没有必要,因为它们与条件f 不匹配[-2:]==“py”
。要将文件名拆分为根目录和扩展名,您还可以考虑使用 <代码>os.path.splitext。
The length check is because the shortest sensible filename is a single character followed by
.py
, which gives at least 4 characters.The last checks seem to be trying to ingore the compiled files with extensions
.pyc
and.pyo
, but it's totally unnecessary as they won't match the conditionf[-2:] == "py"
.For splitting a filename into a root and extension you can also consider using
os.path.splitext
.我建议
作为给定代码的简洁替代方案。
I'd suggest
as a concise alternative to the given code.
此行返回目录中长度至少为 4 个字符的所有文件,不以
o
或c
结尾,但以py
结尾。它会从文件中删除剩余部分,因此blubber.py
将转换为blubber
。我建议以下解决方案:This line returns all files in a directory which are at least 4 characters long, do not end with
o
orc
but end withpy
. It cuts the remainer from the files, soblubber.py
will be converted toblubber
. I suggest the following solution:f[-1]
是可迭代中的最后一个元素,在本例中,是f
的最后一个字母这可能会更清楚:
f[-1]
is the last element in the iterable, in this case, the last letter off
This would probably be clearer: