how can I list only file names in a directory without directory info in the result? I tried
for file in glob.glob(dir+filetype):
print file
give me result
/path_name/1.log,/path_name/2.log,....
but what I do need is file name only: 1.log
, 2.log
, etc. I do not need the directory info in the result. is there a simple way to get rid of the path info? I don't want to some substr on the result. Thank you!
Returns the file name and extension of the specified path string. The Path Class has several useful filename and path methods. This returns just the filename (with extension). If you want just the name without the extension then use Path.GetFileNameWithoutExtension You can just extract the file name from the full path.
How can I get all filenames of a directory (and its subdirectorys) without the full path? Directory.GetFiles (...) returns always the full path! You can extract the filename from full path. var filenames3 = Directory .GetFiles (dirPath, "*", SearchOption.AllDirectories) .Select (f => Path.GetFileName (f));
The GetFileNames formula returns an array that holds the names of all the files in the folder. The INDEX function is used to list one file name per cell, starting from the first one. IFERROR function is used to return blank instead of the #REF! error which is shown when a formula is copied in a cell but there are no more file names to list.
Go to cell A3 (or any cell where you want the list of names to start) and enter the following formula: = IFERROR (INDEX (FileNameList, ROW () -2),"") Drag this down and it will give you a list of all the file names in the folder Want to Extract Files with a Specific Extension??
os.path.basename
:
Return the base name of pathname
path
. This is the second element of the pair returned by passingpath
to the functionsplit()
. Note that the result of this function is different from the Unixbasename
program; wherebasename
for '/foo/bar/' returns 'bar', thebasename()
function returns an empty string ('').
So:
>>> os.path.basename('/path_name/1.log,/path_name/2.log')
'2.log'
import os
# Do not use 'dir' as a variable name, as it's a built-in function
directory = "path"
filetype = "*.log"
# ['foo.log', 'bar.log']
[f for f in os.listdir(directory) if f.endswith(filetype[1:])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With