pythonlist-comprehensionlistdir

How do I sort and filter file names in python using list comprehension?


I am trying to sort the file names in a directory, while filter based on a keywords. It partially works. The sort part works, but as I add filter part I get following error.

TypeError: argument of type 'PosixPath' is not iterable

Working code (without filter),

[path for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime)]

As I add the filter, it does not work,

[path for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime) if "search words" in path]

Thanks in advance.


Solution

  • You should convert the Path object to a string before you can use the in operator to test for a substring:

    [
        path
        for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime)
        if "search words" in str(path)
    ]