Determining whether it's a file or a directory?

D

Dfenestr8

os.listdir("path") returns the names of all the items in a directory ok,
but I need to know whether the item is a file or a directory.

Can anybody tell me how this could be done?
 
P

Peter Otten

Dfenestr8 said:
os.listdir("path") returns the names of all the items in a directory ok,
but I need to know whether the item is a file or a directory.

Can anybody tell me how this could be done?

The standard way would be to perform

os.path.isdir(os.path.join(path, dir_or_file))

on the item in question, but
.... break
....
dirs ['only', 'directories']
files ['some', 'files']

gives you directories and files in separate lists.

Peter
 
A

Aaron Bingham

Dfenestr8 said:
os.listdir("path") returns the names of all the items in a directory ok,
but I need to know whether the item is a file or a directory.

Can anybody tell me how this could be done?
os.path.isdir("path")

Aaron
 
S

Scott David Daniels

Dfenestr8 said:
os.listdir("path") returns the names of all the items in a directory ok,
but I need to know whether the item is a file or a directory.

Can anybody tell me how this could be done?
Some others have shown you how to test if a file is a directory, as
well as how to get a separated list of files and directories, but
I'd like to point out a mistake you are making: you believe a name
is associated with either a file or a directory, but not both. There
are already a few file systems where this is not true, and the trend
seems to be towards, rather than away from this.

The os.walk technique would automatically cope with this situation
(the same name could show up in both lists). Using the os.path.isdir
technique, you are more likely to decide that "if something is a
directory, it is not a file (ie has no non-directory data)."

-Scott David Daniels
(e-mail address removed)
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top