python文件操作

发布于 2024-12-12 02:15:41 字数 516 浏览 2 评论 0原文

请问,这一行的含义是什么:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

や莫失莫忘 2024-12-19 02:15:41

长度检查是因为最短的合理文件名是一个字符后跟 .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']

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 condition f[-2:] == "py".

For splitting a filename into a root and extension you can also consider using os.path.splitext.

[root for (root, ext) in map(os.path.splitext, os.listdir(path)) if ext == '.py']
哭了丶谁疼 2024-12-19 02:15:41

我建议

[f[:-3] for f in glob.iglob("*.py")]

作为给定代码的简洁替代方案。

I'd suggest

[f[:-3] for f in glob.iglob("*.py")]

as a concise alternative to the given code.

聽兲甴掵 2024-12-19 02:15:41

此行返回目录中长度至少为 4 个字符的所有文件,不以 oc 结尾,但以 py 结尾。它会从文件中删除剩余部分,因此 blubber.py 将转换为 blubber。我建议以下解决方案

[x[:-3] for x in os.listdir('.') if x.endswith(".py")]

This line returns all files in a directory which are at least 4 characters long, do not end with o or c but end with py. It cuts the remainer from the files, so blubber.py will be converted to blubber. I suggest the following solution:

[x[:-3] for x in os.listdir('.') if x.endswith(".py")]
时光暖心i 2024-12-19 02:15:41

f[-1] 是可迭代中的最后一个元素,在本例中,是 f 的最后一个字母

这可能会更清楚:

[name for name, ext in [f.rsplit('.', 1) for f in os.listdir('.')] if ext == 'py']

f[-1] is the last element in the iterable, in this case, the last letter of f

This would probably be clearer:

[name for name, ext in [f.rsplit('.', 1) for f in os.listdir('.')] if ext == 'py']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文