Reputation: 7924
I have a file name (mytest.
) with 3 or more suffix (".txt",".shp",".shx",".dbf") in a directory (path = 'C://sample'
). I wish to list all files with the same name
I know with import glob
is possible to list all file with a specific suffix
My question is how to list all "mytest" in the directory
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"]
Upvotes: 2
Views: 8282
Reputation: 54163
If you have other files named mylist
that don't have the extensions you're looking for, this may be a better solution:
import glob
extensions = ["txt","shp","bdf","shx"] # etc
mylist = list()
for ext in extensions:
mylist += glob.glob("mylist.{}".format(ext))
Or probably even easier:
mylist = [item for item in glob.glob('mylist.*') if item[-3:] in extensions]
Upvotes: 3
Reputation: 36141
You're looking for the glob
module, as you said in your question, but with the wildcard on the extension:
import glob
glob.glob("mytest.*")
Example:
$ 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']
>>>
Upvotes: 9