【问题标题】:Return the filenames that end with *.tif, but don't end with *_mask.tif [duplicate]返回以 *.tif 结尾但不以 *_mask.tif 结尾的文件名 [重复]
【发布时间】:2020-11-24 06:27:30
【问题描述】:

使用 Python 3.7.7,我想获取所有不以 *_mask.tif 结尾的图像的列表。

路径中有以*.tif*_mask.tif 结尾的图像。但是下面的代码会返回所有这些。

# Read all the brain images (those that don't end with _mask.tif).
def brain_images_list(path):
    if not isinstance(path, str):
        raise TypeError('path must be a string')

    if not os.path.exists(path):
        raise ValueError('path must exist: ', path)

    if not os.path.isdir(path):
        raise ValueError('path must be a directory: ', path)

    # Save current directory.
    current_dir = os.getcwd()

    # Change current directory to the one we want to look for.
    os.chdir(path)

    # Get brain images list
    brain_images_lst = glob.glob('*.tif')

    # Restore directory
    os.chdir(current_dir)

    return brain_images_lst

我该怎么做?

【问题讨论】:

  • brain_images_lst = glob.glob('*.tif') 你得到了所有的图像。你需要过滤掉那些你不想要的。
  • 是的,我知道我必须做什么,我的问题是我不知道该怎么做。
  • brain_images_lst = [image for image in brain_images_lst if not image.endswith("_mask.tif")]?
  • 这能回答你的问题吗? glob exclude pattern

标签: python


【解决方案1】:

使用glob.glob 并且需要更改目录、执行 glob 并再次更改回来,这让您自己变得复杂。

如果你只想要文件名(不是完整路径),你会更好地使用os.listdir,这可以在不改变目录的情况下完成:

brain_images_lst = [file for file in os.listdir(path)
                    if file.endswith(".tif")
                    and not file.endswith("_mask.tif")]

【讨论】:

    【解决方案2】:

    您最好让自己习惯在使用路径时使用pathlib。在大多数情况下,它比使用os.path 更好,并且您的特定任务可以通过以下方式轻松完成:

    from pathlib import Path
    
    brain_images_lst = [file for file in Path(path).glob("*.tif") if not file.stem.endswith("mask")]
    

    glob 返回 Path 对象,因此如果您只需要文件名,可以更改为 file.name

    【讨论】:

    • 很好,我喜欢。一件小事:这会生成一个 PosixPath 对象列表,这可能是有用的,但为了匹配现有的输出格式(文件名列表),它可能值得改为 [file.name for file in ....]
    • @alaniwi 我完全同意。在代码下查看我的笔记;)
    • 好点——不知道我是怎么错过的:)
    【解决方案3】:

    * 是 glob 的通配符。所以请求获取*.tif 也会返回*_mask.tif。要仅获取*.tif,您需要先按原样存储列表,然后创建所有*_mask.tif 的列表。下面的代码就是这样做的

    brain_images_lst2 = glob.glob('*_mask.tif')

    使用它,我们可以使用这样的循环从*.tif 中删除所有*_mask.tif

    for x in brain_images_lst2:
        brain_images_lst.remove(x)
    

    这应该会导致brain_images_lst 只包含所需的*.tif

    【讨论】:

      【解决方案4】:

      试试这个:

      首先列出file_list中tif类型的所有文件

      只存储result列表中不包含_mask.tif的文件

      import glob
      
      result = []
      file_list= glob.glob(r'C:\Users\vishal\Desktop\Stackoverflow\*.tif') 
      for file in file_list:
          if  '_mask.tif' in file:
              continue
          result.append(file)
      print(result)
      

      【讨论】:

        猜你喜欢
        • 2019-12-31
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2011-07-23
        • 2017-04-29
        • 1970-01-01
        • 2013-10-29
        • 1970-01-01
        相关资源
        最近更新 更多