Reputation: 4725
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!
Upvotes: 10
Views: 16684
Reputation: 10260
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:])]
Upvotes: 3
Reputation: 365737
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'
Upvotes: 30
Reputation: 99630
you can do
import os
[file.rsplit(os.path.sep, 1)[1] for file in glob.glob(dir+filetype)]
Upvotes: 1