-1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
SF12 Study
  • 375
  • 4
  • 18

4 Answers4

1

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]

Shibiraj
  • 769
  • 4
  • 9
1

Simple as that:

import os
print(os.path.basename(os.path.dirname(path)))
funnydman
  • 9,083
  • 4
  • 40
  • 55
0

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
martineau
  • 119,623
  • 25
  • 170
  • 301
-1

The solution to your problem could be to use the library os as follows:

import os
os.chdir('/path/to/folders')
os.system('ls')
B--rian
  • 5,578
  • 10
  • 38
  • 89
ReaperK0v
  • 9
  • 6