Skip to main content
 首页 » 编程设计

Python检查目录中具有特定名称的所有文件

2025年05月04日12Terrylee

我有一个文件名 (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"] 

请您参考如下方法:

您正在寻找 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'] 
>>>