我有一个带有3个或更多后缀的文件名(mytest.
)(“ .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"]
答案 0 :(得分:6)
您正在寻找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']
>>>
答案 1 :(得分:3)
如果您有其他名为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]