【问题标题】:Strip known extension from filename [duplicate]从文件名中删除已知扩展名[重复]
【发布时间】:2019-05-27 18:45:23
【问题描述】:

我有一堆 txt 文件。我想从文件名中去掉.txt(我正在通过os.walk阅读)。

我怎样才能做到这一点?

fileName.rstrip(".txt") 似乎删除了字母 .,t,x 而不是删除子字符串 .txt

【问题讨论】:

  • filename.split('.')[0]filename[:-4] 都可以解决问题。
  • fileName.split(".")[:-1] 怎么样?
  • 在 '.' 处分割如果 '.' 会起作用仅用于将文件名与扩展名分开。但这并不能保证。可能有多个'.'

标签: python python-3.x text


【解决方案1】:

我会推荐使用操作系统库。

name, ext = os.path.splitext(path)

【讨论】:

    【解决方案2】:

    我会使用rpartition(右起partition),并从结果元组中获取第一个elemnet:

    fileName.rpartition(".txt")[0]
    

    rpartition 保证生成一个三元素元组,格式如下:

    (before, sep, after)
    

    因此,对于带有 .txt 扩展名的文件名,例如foobar.txt 你会得到:

    ('foobar', '.txt', '')
    

    对于不以.txt 结尾的文件,例如foobar:

    ('foobar', '', '')
    

    所以在所有情况下都可以获取第一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 2013-03-14
      相关资源
      最近更新 更多