【问题标题】:Python check all file with a specific name in a directoryPython检查目录中具有特定名称的所有文件
【发布时间】:2014-03-03 18:50:03
【问题描述】:

我的文件名 (mytest.) 包含 3 个或更多后缀(“.txt”、“.shp”、“.shx”、。 dbf") 在目录 (path = 'C://sample') 中。我希望列出所有具有相同名称的文件

我知道import glob 可以列出所有带有特定后缀的文件

我的问题是如何列出目录中的所有“mytest”

ex 

mytest.txt
mytest.shp
mytest.bdf
mytest.shx

mylist = ["mytest.txt","mytest.shp","mytest.bdf","mytest.shx"]


mytest.txt
mytest.shp
mytest.bdf
mytest.shx
mytest.pjr

mylist = ["mytest.txt","mytest.shp","mytest.bdf","mytest.shx","mytest.pjr"]

【问题讨论】:

  • 那么,你的问题是什么?
  • 谢谢马克西姆。我的问题是如何列出目录中的所有“mytest”
  • 这里没有字典,所以……你有什么问题?
  • glob.glob('mytest.*') 将完成这项工作。

标签: python list file glob


【解决方案1】:

您正在寻找glob module,正如您在问题中所说,但扩展名上有通配符:

import glob
glob.glob("mytest.*")

例子:

$ ls
a.doc  a.pdf  a.txt  b.doc

$ python
Python 2.7.3 (default, Dec 18 2012, 13:50:09) [...]
>>> import glob
>>> glob.glob("a.*")
['a.doc', 'a.pdf', 'a.txt']
>>>

【讨论】:

    【解决方案2】:

    如果您有其他名为 mylist 的文件没有您要查找的扩展名,这可能是一个更好的解决方案:

    import glob
    
    extensions = ["txt","shp","bdf","shx"] # etc
    
    mylist = list()
    for ext in extensions:
        mylist += glob.glob("mylist.{}".format(ext))
    

    或者可能更简单:

    mylist = [item for item in glob.glob('mylist.*') if item[-3:] in extensions]
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      相关资源
      最近更新 更多