【问题标题】:How to list a file starting with "2019_03" with extension ".text" in Python [duplicate]如何在Python中列出以“2019_03”开头、扩展名为“.text”的文件[重复]
【发布时间】:2020-01-22 06:44:52
【问题描述】:

我在 linux 系统中有很多文件,比如:

2019_03_01.text
2019_03_01.jpg
2019_03_01.png
2019_03_02.text
2019_03_02.jpg
2019_03_02.png
...
.
2019_09_21.text
2019_09_21.jpg
2019_09_21.png
.

我只想在 python 中列出以“.text”开头的“2019_03”。我在linux终端上运行命令如下:

ls /path/[2019_03]* | grep /*.text

我如何在 python 中做到这一点?

【问题讨论】:

  • 你试过什么?包括您的代码。你遇到了什么问题?
  • 您使用欺骗 - 而不是“endswith”或 *.txt 文件模式,您调整模式以匹配您的文件...
  • 实际上我使用 glob 和 os 模块,但我无法在这里分享。

标签: python python-3.x linux terminal ls


【解决方案1】:

glob 模块将成为您的朋友。

import glob

list_of_files = glob.glob('/path/2019_03*.text')

【讨论】:

    【解决方案2】:

    您可以简单地使用 python (re) 中的正则表达式库,然后搜索“.text”。要获取文件列表,我们可以使用 os 模块列出文件:

    # ~ Libraries ~ #
    import os
    import re
    
    # ~ Directory ~ #
    path_to_directory = '/path/to/directory/'
    
    # ~ List of files ~ #
    file_list = os.listdir(path_to_dir)
    
    # ~ Get only files with .text extensions ~ #
    file_text = [x for x in file_list if re.search('.text',x)]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2014-03-29
      相关资源
      最近更新 更多