代码之家  ›  专栏  ›  技术社区  ›  bapors

在python中的目录中列出具有特定扩展名的文件的第一部分

  •  0
  • bapors  · 技术社区  · 8 年前

    我正在尝试提取具有特定扩展名的文件的第一部分( .txt ),我试图使它尽可能短,甚至在一行中:

    path = "/home/inputs"
    text_files = [f for f in os.listdir("path") if f.endswith('.txt')]
    
    print(text_files)
    >['new_categorized.txt', 'new.txt', '2017_input.txt']
    

    所以在这之前,它是有效的。但是,我无法获得以下所需列表:

    >['new_categorized', 'new', '2017_input']
    

    我尝试过:

    print(os.path.splitext(text_files[0])[0])
    > new_categorized
    

    但这样,我就丢失了其他文件名。我怎样才能得到全部?

    6 回复  |  直到 8 年前
        1
  •  1
  •   iBug    8 年前

    你需要一个小技巧:

    path = "/home/inputs"
    text_files = ['.'.join(f.split('.')[:-1]) for f in os.listdir(path) if f.endswith('.txt')]
    

    诀窍如下:

    '.'.join(f.split('.')[:-1])
    

    它首先将文件名按点拆分,然后删除最后一个文件名,并用点将它们连接起来。这有效地去除了最后一个点和后面的所有内容,如果没有点,则什么也不做。

        2
  •  1
  •   Bailey Parker    8 年前

    对于Python 3.4及以上版本,请尝试使用 pathlib :

    print([path.stem for path in Path('/home/inputs').glob('*.txt')])
    

    Path.glob() 与您的 os.listdir + f.endswith('.txt') 然后,为了得到最后一条斜杠之后但在扩展之前的路径部分,我们只需要使用 .stem 属性。

    使用现有代码,“丢失其他文件名”,因为您只调用 os.path.splittext 在…上 text_files[0] . 要对其中多个进行此操作,请使用列表理解:

    print([os.path.splitext(path)[0] for path in text_files])
    
        3
  •  1
  •   Shashank    8 年前

    我刚刚编辑了你代码中的两个主要内容。首先,我使用path作为变量,而不是字符串。其次,我使用切片来获得所需的结果。

    因此,您可以尝试以下方法:

    >>> import os
    >>> path = "/home/shashank"
    
    >>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
    >>> text_files
    ['temp.txt', 'myfile.txt', 'angular.txt', 'y.txt']
    >>>
    >>> text_files = [f[:-4] for f in os.listdir(path) if f.endswith('.txt')]
    >>> text_files
    ['temp', 'myfile', 'angular', 'y']
    
        4
  •  1
  •   jesper_bk    8 年前

    如果希望它尽可能短,请使用 map 具有lambda表达式的函数:

    print(list(map(lambda f: os.path.splitext(f)[0], text_files)))
    
        5
  •  1
  •   mahdi_12167    8 年前

    您可以这样做:

    [f.split(".")[0] for f in os.listdir(path) if f.endswith('.txt')]
    
        6
  •  1
  •   jpp    8 年前

    可以采用纯功能方法:

    import os
    
    text_files = ['new_categorized.txt', 'new.txt', '2017_input.txt']
    list(zip(*map(os.path.splitext, text_files)))[0]
    
    # ('new_categorized', 'new', '2017_input')
    

    这里的输出是元组而不是列表。