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 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'
Getting a directory name from a filename
There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH
(260) characters.
How do I get the directory from a file's full path?
If you've definitely got an absolute path, use Path.GetDirectoryName(path)
.
If you might only get a relative name, use new FileInfo(path).Directory.FullName
.
Note that Path
and FileInfo
are both found in the namespace System.IO
.
How do I get the file name from a String containing the Absolute file path?
just use File.getName()
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());
using String methods:
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+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 from full file path
See DirectoryInfo.Name:
string dirName = new DirectoryInfo(@"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;
Get the directory name (not a path) of a given file path in Golang
You can use filepath.Base
to get the last element of the directory.
For example:
package main
import (
"fmt"
"path/filepath"
)
func main() {
paths := []string{
"/home/arnie/amelia.jpg",
"/mnt/photos/",
"rabbit.jpg",
"/usr/local//go",
}
for _, p := range paths {
dir := filepath.Dir(p)
parent := filepath.Base(dir)
fmt.Printf("input: %q\n\tdir: %q\n\tparent: %q\n", p, dir, parent)
}
}
Returns:
input: "/home/arnie/amelia.jpg"
dir: "/home/arnie"
parent: "arnie"
input: "/mnt/photos/"
dir: "/mnt/photos"
parent: "photos"
input: "rabbit.jpg"
dir: "."
parent: "."
input: "/usr/local//go"
dir: "/usr/local"
parent: "local"
(example adapted from the filepath examples)
Get directory of a file name in Javascript
I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.
path = path.substring(0,path.lastIndexOf("\\")+1);
How to get just the parent directory name of a specific file
Use File
's getParentFile()
method and String.lastIndexOf()
to retrieve just the immediate parent directory.
Mark's comment is a better solution thanlastIndexOf()
:
file.getParentFile().getName();
These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File
). When getParentFile()
is null you'll need to resort to using lastIndexOf
, or use something like Apache Commons' FileNameUtils.getFullPath()
:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils
class to grab the name from the result, use lastIndexOf
, etc.
Related Topics
C++ Why the Assignment Operator Should Return a Const Ref in Order to Avoid (A=B)=C
Glpixelstorei(Gl_Unpack_Alignment, 1) Disadvantages
Declaring a Pointer to Multidimensional Array and Allocating the Array
How to Iterate Over a Constant Vector
How to Format Date Time Object with Format Dd/Mm/Yyyy
What's the Best Way to Check If a File Exists in C++? (Cross Platform)
Why Is "\" an Escape Sequence in C/C++
How to Prevent Non-Specialized Template Instantiation
Do Polymorphism or Conditionals Promote Better Design
What Is the Right Approach When Using Stl Container for Median Calculation
Detect Gcc as Opposed to Msvc/Clang with MACro
Using Emit VS Calling a Signal as If It's a Regular Function in Qt
When Is It Safe to Call This-> in Constructor and Destructor
C++ Implicit Conversion (Signed + Unsigned)
In Cmake, How to Work Around the Debug and Release Directories Visual Studio 2010 Tries to Add