-1

I'm trying to get the files name for a path. But every time I run this code below I only get the name of the parent folder instead

    for file in files:
        if file.endswith("png") or file.endswith("jpg"):
            path = os.path.join(root,file)
            print(path)
            label = os.path.basename(os.path.dirname(path))
            print(label)

I get these results :

D:\AI\Deep learning\face generator\images\chris evans 1.jpg
images
D:\AI\Deep learning\face generator\images\chris evans 2.jpg
images

and so on

My expected results are

D:\AI\Deep learning\face generator\images\chris evans 1.jpg
chris evans 1.jpg
D:\AI\Deep learning\face generator\images\chris evans 2.jpg
chris evans 2.jpg
Houmes
  • 71
  • 1
  • 1
  • 7
  • 1
    Please read https://stackoverflow.com/help/how-to-ask, use correct upper case letters and provide a better view of input and expected output. – buhtz Feb 09 '22 at 12:52

1 Answers1

1

You should use pathlib (Python >= 3.4) for this.

from pathlib import Path

p = Path('D:\AI\Deep learning\face generator\images\chris evans 1.jpg')
filename = p.name
print(filename)
buhtz
  • 10,774
  • 18
  • 76
  • 149