【问题标题】:How can I strip the file extension from a list full of filenames?如何从完整的文件名列表中删除文件扩展名?
【发布时间】:2015-01-03 00:51:16
【问题描述】:

我正在使用以下内容获取一个列表,其中包含一个名为 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 循环从列表中的所有项目中删除文件扩展名。

正确的做法是什么?

【问题讨论】:

    标签: python list path file-extension


    【解决方案1】:

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

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

    但是如果你想要/需要一个 for 循环,等效的代码是:

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多