user11294454
user11294454

Reputation:

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.

Upvotes: 2

Views: 1350

Answers (2)

lmiguelvargasf
lmiguelvargasf

Reputation: 69933

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.

Upvotes: 1

Nathan
Nathan

Reputation: 10326

I recommend using pathlib.Path over os most of the time. Try this, for example:

from pathlib import Path

directory = Path("C:/Users/test/Desktop/test/sign off img")
choices = [path.name for path in directory.glob("*.jpg")]

Upvotes: 0

Related Questions