How can I strip the file extension from a list full of filenames?

喜欢而已 提交于 2019-12-01 15:31:06

问题


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:


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.



来源:https://stackoverflow.com/questions/27750611/how-can-i-strip-the-file-extension-from-a-list-full-of-filenames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!