Gary
Gary

Reputation: 4725

how can I get filenames without directory name

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

Answers (3)

timss
timss

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

abarnert
abarnert

Reputation: 365737

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'

Upvotes: 30

karthikr
karthikr

Reputation: 99630

you can do

import os
[file.rsplit(os.path.sep, 1)[1] for file in glob.glob(dir+filetype)]

Upvotes: 1

Related Questions