Search code examples
pythonpathfilenamesglob

How to call base name of files from a specific path in python?


I have many files in a specific path such :/a/b/c/*.tif. I wnat to get their basenames as a list.

import glob
import pandas as pd

pattern = '/a/b/c/*.tif'
filenames = [path.basename(x) for x in glob(pattern)]
pd.DatetimeIndex([pd.Timestamp(f[:9]) for f in filenames])

This code has TypeError: 'module' object is not callable error.


Solution

  • You want to call the function glob.glob instead of using the module name glob in your first list comprehension, which led to the TypeError: 'module' object is not callable

    Also you should import the os module to do os.path.basename

    import os
    import glob
    import pandas as pd
    
    pattern = '/a/b/c/*.tif'
    #Use glob.glob to call the function
    filenames = [os.path.basename(x) for x in glob.glob(pattern)]
    pd.DatetimeIndex([pd.Timestamp(f[:9]) for f in filenames])