Search code examples
pythonpython-3.xfiledirectoryworking-directory

How do I get the folder of the known file directory?


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.


Solution

  • Use basename and dirname,

    import os
    path = 'C:/Users/ExUser/Documents/Folder/Player/To-Do.txt'
    os.path.basename(os.path.dirname(path))
    

    Or Simply

    path.split('/')[-2]