What command can I execute using python to find the folder of the file(the directory is known) using python?
For example, I have "C:/Users/ExUser/Documents/Folder/Player/To-Do.txt"
, I just need the "Player"
part.
What command can I execute using python to find the folder of the file(the directory is known) using python?
For example, I have "C:/Users/ExUser/Documents/Folder/Player/To-Do.txt"
, I just need the "Player"
part.
import os
path = 'C:/Users/ExUser/Documents/Folder/Player/To-Do.txt'
os.path.basename(os.path.dirname(path))
Or Simply
path.split('/')[-2]
You can use the parent
property of a pathlib.Path
:
from pathlib import Path
path = Path("C:/Users/ExUser/Documents/Folder/Player/To-Do.txt")
print(f'path.parent.as_posix(): {path.parent.as_posix()}')
Output:
path.parent.as_posix(): C:/Users/ExUser/Documents/Folder/Player