Search code examples
pythonglob

Cut down path name in Python


This is my current code:

directory = "C:/Users/test/Desktop/test/sign off img"
choices = glob.glob(os.path.join(directory, "*.jpg"))
print(choices)

This will return me every single path to all .JPG files inside that specific folder.

As an example, here is the output for the current above code:

['C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL - signed.jpg', 'C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL.jpg']

How can I get the output to only return the ending of the path?

This is my desire outcome:

['SFDG001 0102400OL - signed.jpg', 'SFDG001 0102400OL.jpg']

Same path, but just the end string is returned.


Solution

  • You can use the os.listdir function:

    >>> import os
    >>> files = os.listdir("C:/Users/test/Desktop/test/sign off img")
    >>> filtered_files = [file for file in files if 'signed' in file]
    

    As you can see in thee docs, os.listdir uses the current directory as default argument, i.e., if you don't pass a value. Otherwise, it will use the path you pass to it.