Get a File Name from a Path

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));

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Path.GetFileName

Returns the file name and extension of a file path that is represented
by a read-only character span.


Path.GetFileNameWithoutExtension

Returns the file name without the extension of a file path that is
represented by a read-only character span.


The Path class is wonderful.

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.

Extract the filename from a path

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf

How to extract the file name from a file path?

If all you want to do is truncate the file paths to just the filename, you can use os.path.basename:

for file in files:
fname = os.path.basename(file)
dict_[fname] = (pd.read_csv(file, header=0, dtype=str, encoding='cp1252')
.fillna(''))

Example:

os.path.basename('Desktop/test.txt')
# 'test.txt'

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

Get file name from absolute path in Nodejs?

Use the basename method of the path module:

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

Here is the documentation the above example is taken from.

How to get the file name from a full path using JavaScript?

var filename = fullPath.replace(/^.*[\\\/]/, '')

This will handle both \ OR / in paths

Flutter: Get the filename of a File

You can use the basename function from the dart path library:

import 'package:path/path.dart';

File file = new File("/dir1/dir2/file.ext");
String basename = basename(file.path);
# file.ext


Related Topics



Leave a reply



Submit