Determining whether it's a file or a directory?

Discussion in 'Python' started by Dfenestr8, Oct 8, 2004.

  1. Dfenestr8

    Dfenestr8 Guest

    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?
     
    Dfenestr8, Oct 8, 2004
    #1
    1. Advertisements

  2. Dfenestr8

    Peter Otten Guest

    The standard way would be to perform

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

    on the item in question, but
    .... break
    ....
    gives you directories and files in separate lists.

    Peter
     
    Peter Otten, Oct 8, 2004
    #2
    1. Advertisements

  3. os.path.isdir("path")

    Aaron
     
    Aaron Bingham, Oct 8, 2004
    #3
  4. 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
     
    Scott David Daniels, Oct 8, 2004
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.