Question

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"]
Was it helpful?

Solution

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']
>>>

OTHER TIPS

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]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top