I have the following code which appends images to a list. How can I just make the names of the indexes of the list contain the filename only instead of the whole file path.
Here is my code:
def getFiles(path):
for file in os.listdir(path):
if file.endswith(".JPG"):
list.append(os.path.join(path, file))
Instead of getting a list that has the following results:
[drive/img/img1.jpg, drive/img/img2.jpg ...]
I want a list that has the following results:
[img1.jpg, img2.jpg]
CodePudding user response:
My favorite library to work with paths is pathlib. In this case you can leverage the .suffix and the .name attributes of the Path objects.
Here's some toy code:
from pathlib import Path
path = Path(my_path)
fnames = list()
for p in path.iterdir():
if p.suffix==".JPG":
fnames.append(p.name)
CodePudding user response:
This should do it.
def getFiles(path):
mylist = []
for file in os.listdir(path):
if file.endswith(".JPG"):
mylist.append(os.path.basename(file))
return mylist
images = getFiles("C:\\Images")
print(images)
CodePudding user response:
You can try with following code. In this case you split the name from the extension and only take into account the filename at position "[0]".
def getFiles(path):
for file in os.listdir(path):
if file.endswith(".JPG"):
ll.append(file)
