Reputation: 37
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 ?
Upvotes: 1
Views: 316
Reputation: 601361
I'd suggest
[f[:-3] for f in glob.iglob("*.py")]
as a concise alternative to the given code.
Upvotes: 2
Reputation: 837926
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']
Upvotes: 3
Reputation: 12920
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")]
Upvotes: 1
Reputation: 12339
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']
Upvotes: 0