How Does One Extract Each Folder Name from a Path

Getting the folder name from a full filename path

I would probably use something like:

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name.

This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. If it's unknown whether the path ends in a filename or folder name - then it requires that you check the actual path to see if a file/folder exists at the location first. In that case, Dan Dimitru's answer may be more appropriate.

Get a folder name from a path

string a = new System.IO.DirectoryInfo(@"c:\server\folderName1\another name\something\another folder\").Name;

Extract folder name from path in batch file

I think this is what you're looking for:

@echo off
FOR /F "delims=" %%F IN ('dir /B /A /S *') DO (
for %%D in ("%%~dpF\.") do echo %%~nxD
)
pause

Extract the Folder Names and Levels from paths SQL Server / ORACLE

Perhaps this will help

Example

Select A.Folder_ID
,A.Folder_Name
,Parent_Folder = Pos2
,Lvl = len(Path)-len(replace(Path,'/',''))
From Table1 A
Cross Apply (
Select Pos1 = reverse(trim(JSON_VALUE(S,'$[0]')))
,Pos2 = reverse(trim(JSON_VALUE(S,'$[1]')))
From ( values ( '["'+replace(replace(reverse(Path),'"','\"'),'/','","')+'"]' ) ) A(S)
) B

Returns

Folder_ID   Folder_Name     Parent_Folder   Lvl
1 Folder1 NULL 0
2 Folder1_1 Folder1 1
3 Folder1_1_1 Folder1_1 2
4 Folder1_2 Folder1 1
5 Folder1_2_1 Folder1_2 2
6 Folder1_2_2 Folder1_2 2

How to extract the last folder and file name from file path in python

Possible solution is to use split() function.

text_string = r'''G:\folder1\folder2\folder3\folder4\folder5\fold2/197320-6-10-0.wav'''

data = text_string.split("\\")[-1]

print(data)

Prints

fold2/197320-6-10-0.wav

Extracting folder name from file path

Split it using the blackslash, and then take the last item in the array:

Sub test()
Dim sText As String
Dim vSplit As Variant

sText = "O:\Folder1\Folder2\Folder3\2020\02 Feb\14 Feb 2020"

' make sure folder string does not end with a backslash
If Right$(sText, 1) = "\" Then sText = Left$(sText, Len(sText) - 1)

' Split into an array based on the backslash
vSplit = Split(sText, "\")

' set cell C1 equal to the last item in the split array
Range("C1") = vSplit(UBound(vSplit))

End Sub

Python: Extract folder name from path

You can use os.path.basename:

>>> path = "/folder_a/folder_b/folder_c/folder_d"
>>> import os
>>> os.path.basename(path)
'folder_d'


Related Topics



Leave a reply



Submit