Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get filenames without directory name

Tags:

python

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!

like image 363
Gary Avatar asked Apr 18 '13 18:04

Gary


People also ask

How do I get the name of a file without extension?

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

How to list all the files in a folder using getfilenames?

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.

How to extract all names of files in a folder?

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??


2 Answers

os.path.basename:

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 ('').

So:

>>> os.path.basename('/path_name/1.log,/path_name/2.log')
'2.log'
like image 115
abarnert Avatar answered Oct 08 '22 14:10

abarnert


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:])]
like image 3
timss Avatar answered Oct 08 '22 15:10

timss