How to separate directory list and file list?

G

Gonnasi

With
glob.glob("*")
or
os.listdir(cwd)

I can get a combined file list with directory list, but I just wanna a
bare file list, no directory list. How to get it?

Tons of thanks in advance!

Gonnasi
 
O

Oliver Andrich

Hi,

2005/10/23 said:
With

I can get a combined file list with directory list, but I just wanna a
bare file list, no directory list. How to get it?

don't know if it is the best solution, but it looks nice. :)

path = "/home/test"
files = [fn for fn in os.listdir(path) if
os.path.isfile(os.path.join(path, fn))]

This gives you just the list of files in a given directory.

Best regards,
Oliver
 
F

Fredrik Lundh

Gonnasi said:
With

I can get a combined file list with directory list, but I just wanna a
bare file list, no directory list. How to get it?

use os.path.isfile on the result.

for file in glob.glob("*"):
if not os.path.isfile(file):
continue
... deal with file ...

for file in os.listdir(cwd):
file = os.path.join(cwd, file)
if not os.path.isfile(file):
continue
... deal with file ...

files = map(os.path.isfile, glob.glob("*"))

files = (file for file in os.listdir(cwd) if os.path.isfile(os.path.join(cwd, file)))

etc.

</F>
 
P

Peter Hansen

Gonnasi said:
With

I can get a combined file list with directory list, but I just wanna a
bare file list, no directory list. How to get it?

Using Jason Orendorff's path module, it's just this:


-Peter
 
A

Alex Martelli

Gonnasi said:
With

I can get a combined file list with directory list, but I just wanna a
bare file list, no directory list. How to get it?

I see everybody's suggesting os.path.* solutions, and they're fine, but
an interesting alternative is os.walk:

__, thedirs, thefiles = os.walk('.').next()

thefiles is the list of filenames (and thedirs is the list of directory
names), and each is sorted alphabetically. (I'm assigning to '__' the
absolute path of the current directory, meaning I intend to ignore it).
An expression that just provides the filename list is

os.walk('.').next()[2]

although this may be a tad too obscure to recommend it!-)


Alex
 
G

Gonnasi

Lots of thanks for your help, My code can return the right result now.

Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top