Search code examples
pythonlistfileglob

Python check all file with a specific name in a directory


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

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