如何从充满文件名的列表中删除文件扩展名?

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

我正在使用以下命令获取一个列表,其中包含名为 tokens 的目录中的所有文件:

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

输出:

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

我想从此列表中的每一项中删除扩展名 .py。我设法单独使用 os.path.splitext:

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

我确定我做得太过了,但我想不出一种方法来使用 for 循环从列表中的所有项目中删除文件扩展名。

正确的做法是什么?

您实际上可以在一行中使用 list comprehension:

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

但是如果你 want/need 一个 for 循环,等效代码将是:

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

另请注意,我保留了 os.path.splitext(x)[0] 部分。这是 Python 中从文件名中删除扩展名的最安全方法。 os.path 模块中没有专门用于此任务的函数,并且使用 str.split 手工制作解决方案或其他容易出错的方法。