How can I strip the file extension from a list ful

2019-02-22 04:21发布

I am using the following to get a list with all the files inside a directory called tokens:

import os    
accounts = next(os.walk("tokens/"))[2]

Output:

>>> print accounts
['.DS_Store', 'AmieZiel.py', 'BrookeGianunzio.py', 'FayPinkert.py', 'JoieTrevett.py', 'KaroleColinger.py', 'KatheleenCaban.py', 'LashondaRodger.py', 'LelaSchoenrock.py', 'LizetteWashko.py',  'NickoleHarteau.py']

I want to remove the extension .py from each item in this list. I managed to do it individually using os.path.splitext:

>>> strip = os.path.splitext(accounts[1])
>>> print strip
('AmieZiel', '.py')
>>> print strip[0]
AmieZiel

I'm sure I'm overdoing things, but I can't figure out a way to strip the file extension from all the items in the list with a for-loop.

What would be the proper way to do it?

1条回答
做个烂人
2楼-- · 2019-02-22 05:06

You can actually do this in one line with a list comprehension:

lst = [os.path.splitext(x)[0] for x in accounts]

But if you want/need a for-loop, the equivalent code would be:

lst = []
for x in accounts:
    lst.append(os.path.splitext(x)[0])

Notice too that I kept the os.path.splitext(x)[0] part. This is the safest way in Python to remove the extension from a filename. There is no function in the os.path module dedicated to this task and handcrafting a solution with str.split or something would be error prone.

查看更多
登录 后发表回答