0

I have multiple files and I need to extract the folder from its path.

folder1/folder2/templates/xyz.yaml

folder1/folderx/templates/abc.yaml

How can i extract folder2 and folderx in python.

Rishi
  • 21
  • 3
  • 1
    If they are stored as strings, and for example called `path`, then you can do `path.split('/')[1]`. – ChrisOram Aug 06 '21 at 15:28
  • 1
    Perhaps the `os.path.dirname()` or `os.path.split()` functions may be of use. An advantage is that it’s portable, whereas using the `str.split()` function is not always guaranteed to work. – S3DEV Aug 06 '21 at 15:39
  • Does this answer your question? [Get folder name of the file in Python](https://stackoverflow.com/questions/33372054/get-folder-name-of-the-file-in-python) – S3DEV Aug 06 '21 at 15:44
  • i modified a little and made like this: import os print( f"Full Path :{diff}" ) nmFolders = diff.split( os.path.sep ) print( "List of Folders:", nmFolders ) print( f"Program Name :{nmFolders[-1]}" ) print( f"Folder Name :{nmFolders[-2]}" ) print( f"Folder Parent:{nmFolders[-3]}" ) This works well for single file, But what if i have multiple files which i need to iterate through. – Rishi Aug 06 '21 at 16:10
  • @Rishi - Please update the **question** accordingly, with input examples *and* the expected output. – S3DEV Aug 06 '21 at 16:43
  • i found out a way to do it with path.split("\n") and str.split(os.path.sep). – Rishi Aug 10 '21 at 17:49

0 Answers0