【问题标题】:Take everything out of a file name except from numbers [closed]从文件名中删除除数字之外的所有内容[关闭]
【发布时间】:2018-05-18 22:11:39
【问题描述】:

所以我有文件3D_492.png,我试图摆脱所有最后一个下划线之后的数字。我该怎么办?

我想让3D_492.png变成492.png

更多示例: Anniversary_1_Purple_710.png变成710.png

它们都在文件夹\Images

编辑:我很笨,忘了说我想用新名称重命名文件。

谢谢

【问题讨论】:

    标签: python string python-3.x filenames


    【解决方案1】:

    使用拆分:

    filename = "3D_710.png"
    # create a list of the parts of the file name separated by "_"
    filename_parts = filename.split("_")
    # new_file is only the last part
    new_file = filename_parts[-1]
    print new_file
    # 710.png
    

    包括重命名的完整示例,假设 Images 是相对于包含我们的 Python 脚本的目录:

    from os import listdir, rename
    from os.path import isfile, join, realpath, dirname
    
    dir_path = dirname(realpath(__file__))
    images_path = join(dir_path, "Images")
    only_files = [f for f in listdir(images_path) if isfile(join(images_path, f))]
    for file in only_files:
        filename_parts = file.split("_")
        # new_file is only the last part
        new_file = filename_parts[-1]
        rename(join(images_path, file), join(images_path, new_file))
    

    【讨论】:

    • 这非常有效,谢谢! 也感谢其他人的回答。
    【解决方案2】:

    str.rpartition 的完美工作:

    >>> s = "3D_492.png"
    >>> start, sep, end = s.rpartition('_')
    >>> end
    '492.png'
    

    保证返回三个元素,总和为原始字符串。这意味着您始终可以获得“尾巴”的第二个元素:

    >>> 'Anniversary_1_Purple_710.png'.rpartition('_')[2]
    '710.png'
    

    拼凑:

    import os
    os.chdir('\Images')
    
    for old_name in os.listdir('.'):
        new_name = old_name.rpartition('_')[2]
        if not exists(new_name):
            os.rename(old_name, new_name)
    

    【讨论】:

      【解决方案3】:

      这是一种方法,使用os.path.basename 然后str.split 提取最后一个下划线后的字符:

      import os
      
      lst = ['3D_492.png', 'Anniversary_1_Purple_710.png']
      
      res = [os.path.basename(i).split('_')[-1] for i in lst]
      
      print(res)
      
      ['492.png', '710.png']
      

      【讨论】:

        【解决方案4】:

        听起来您只想拆分 _ 并忽略除最后一个结果之外的所有内容。

        *_, result = fname.split("_")
        # or:
        # result = fname.split("_")[-1]
        

        使用os.rename完成重命名

        for fname in fnames:  # where fnames is the list of the filenames
            *_, new = fname.split("_")
            os.rename(fname, new)
        

        请注意,如果您想使用绝对路径执行此操作(例如,如果 fnames 看起来像 ["C:/users/yourname/somefile_to_process_123.png", ...],则需要使用 os.path.split 进行更多处理)

        for fpath in fnames:
            *dir, basename = os.path.split(fpath)
            *_, newname = basename.split("_")
            newpath = os.path.join(dir[0], newname)
            os.rename(fpath, newpath)
        

        【讨论】:

        • 由于他们只想要最后一个结果,可能要考虑fname.rsplit('_', 1)[1],因为我相信它会稍微快一些
        • @chrisz 可以,但似乎没有必要(微优化等等)。请注意,按 1 而不是 -1 索引的健壮性稍差(因为如果文件名没有下划线,它会以 IndexError 失败)
        【解决方案5】:

        您可以使用正则表达式来搜索扩展名之前的数字。

        import re
        
        def update_name(name):
            return re.search(r'\d+\..*', name).group()
        
        update_name('3D_492.png') # '492.png'
        

        【讨论】:

          猜你喜欢
          • 2021-04-20
          • 1970-01-01
          • 2010-11-26
          • 2015-07-22
          • 1970-01-01
          • 1970-01-01
          • 2011-11-08
          • 2022-01-13
          • 1970-01-01
          相关资源
          最近更新 更多