Extract Only Folder Name Right Before Filename from Full Path

Extract only folder name right before filename from full path

This may solve:

filePath <- "/data/folder1/subfolder1/foo.dat"

basename(dirname(filePath))

http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1

Extract only folder name right before filename from full path

This may solve:

filePath <- "/data/folder1/subfolder1/foo.dat"

basename(dirname(filePath))

http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1

Get folder name of the file in Python

You can use dirname:

os.path.dirname(path)

Return the directory name of pathname path. This is the first element
of the pair returned by passing path to the function split().

And given the full path, then you can split normally to get the last portion of the path. For example, by using basename:

os.path.basename(path)

Return the base name of pathname path. This is the second element of
the pair returned by passing path to the function split(). Note that
the result of this function is different from the Unix basename
program; where basename for '/foo/bar/' returns 'bar', the basename()
function returns an empty string ('').


All together:

>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'

How can I extract the folder path from file path in Python?

You were almost there with your use of the split function. You just needed to join the strings, like follows.

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

Although, I would recommend using the os.path.dirname function to do this, you just need to pass the string, and it'll do the work for you. Since, you seem to be on windows, consider using the abspath function too. An example:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

If you want both the file name and the directory path after being split, you can use the os.path.split function which returns a tuple, as follows.

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

Extract file name from path, no matter what the os/path format

Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.

Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.

import ntpath
ntpath.basename("a/b/c")

Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:

def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)

Verification:

>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 
... 'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']


(1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c' always refers to the file b\c in the a folder, while on Windows, it always refers to the c file in the b subfolder of the a folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.

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.

Extract folder name and filename from FilePath using scala

As a supplement to what @PavelOliynyk suggested, here's what you can do:

val list = List(
"/repository/resources/2016-03-04/file.csv",
"/repository/resources/2016-03-04/file2.csv",
"/repository/resources/2016-03-05/file3.csv",
"/repository/resources/2016-03-05/file4.csv")

val datesAndFiles = list.map(_.split("/").takeRight(2).toList)

This is presuming that last two items in every string will be date and filename. I converted it to list so that you can easily pattern-match if you need to process it further, e.g. this is how you would get a tuple for each row:

val datesAndFileTuples = datesAndFiles.map({
case date :: file :: Nil => (date, file)
})

That gives you a tuple for each date-file pair. If you'd rather separate them into dates and files (each in their own list), you can do this:

val (dates :: files :: Nil) = datesAndFiles.transpose

which gives you back two lists, one with dates and one with file names.

How to extract directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ VAR='/home/pax/file.c'
$ DIR="$(dirname "${VAR}")" ; FILE="$(basename "${VAR}")"
$ echo "[${DIR}] [${FILE}]"
[/home/pax] [file.c]

They're not internal bash commands but they are part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

How to extract file name from path?

This is taken from snippets.dzone.com:

Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'

If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function


Related Topics



Leave a reply



Submit