Python Forum

Full Version: only print the last folder ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi, I know I can get the name of the last folder using os.path.basename and os.path.normpath.

src_1 = "/storage/emulated/0/Documents/TAX/December_2021"
src_2 = "/storage/emulated/0/Documents/TAX/March_2022"
print(os.path.basename(os.path.normpath(src_1)))

gives me: December_2021

Nice.

HOWEVER, this doesn't work, if I use a "wildcard" as the last folder:
src = "/storage/emulated/0/Documents/TAX/{name of this folder}"

print(os.path.basename(os.path.normpath(src)))

I only get {name of this folder} and not December_2021 or March_2022.

Is there a way to do it this way or do I need another approach?
Thanks for any help!
What do you mean with wildcard?

and why

print(os.path.basename(os.path.normpath(src_1)))

That's enough

print(os.path.basename(src_1))
Hi, thank you for replying.

I want the print-out to be whatever folder I am in. So if I'm in folder "December_2021" it should print "December_2021". If I'm in "May_2022" it should print that.

Always the one I'm in. That's supposed to be the variable. And in my file structure it is the last folder. That's how it is on my computer.

The post is really about the variable. I can't make that work as you can see...
If you want the name of the current working directory, use
from pathlib import Path
name = Path.cwd().name
If you want the name of the directory where the file executing this code is use
name = Path(__file__).parent.name
(May-21-2022, 09:01 PM)User3000 Wrote: [ -> ]Please post all code, output and errors (it it's entirety) between their respective tags.
i don't know if you have this saved as an action button since it is needed so often. it needs s/it it/in it/