【问题标题】:List the files by giving the directory and a part of the file name along with extension通过提供目录和部分文件名以及扩展名来列出文件
【发布时间】:2019-01-04 09:39:40
【问题描述】:

通过提供目录和部分文件名以及扩展名来列出文件的有效方法。

For Ex:- Directory = "/home/Dell/Projects/"
         File Name Starts with = "sample_"
         Extension = ".csv"

我可能在提到的目录中有以下文件,

1. "/home/Dell/Projects/sample_1.csv"
2. "/home/Dell/projects/sample_2019_01_04.csv"
3. "/home/Dell/Projects/sample_2.pkl"
4. "/home/Dell/Projects/sample_3.txt"

在上面的 4 个文件中,我应该从上面的 python 列表中获取 file.1 和 file.2。

【问题讨论】:

    标签: python-3.x file directory


    【解决方案1】:

    在os&fnmatch库的帮助下,可以得到想要的结果。

    import os, fnmatch
    listOfFiles = os.listdir('/home/Dell/Projects/')  
    pattern = "sample_*.csv"  
    for entry in listOfFiles:  
        if fnmatch.fnmatch(entry, pattern):
            print ("Entry :: ", entry)
    

    输出将是,

    Entry :: sample_1.csv
    Entry :: sample_2019_01_04.csv
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2011-05-17
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多