Check if an entry is a file or directory in Python

by

To check whether an entry is a file or a directory in python, use the os.path.isdir() method. To read some file attributes, use the os.stat() method. The following code will read all entries in the current directory and then print out whether the entry is a file or a directory together with the time the file/dir was created.


import os, time
dirList = os.listdir("./")
for d in dirList:
    if os.path.isdir(d) == True:
        stat = os.stat(d)
        created = os.stat(d).st_mtime
        asciiTime = time.asctime( time.gmtime( created ) )
        print d, "is a dir  (created", asciiTime, ")"
    else:
        stat = os.stat(d)
        created = os.stat(d).st_mtime
        asciiTime = time.asctime( time.gmtime( created ) )
        print d, "is a file (created", asciiTime, ")"
Advertisements

Tags: , ,

25 Responses to “Check if an entry is a file or directory in Python”

  1. Scott Says:

    This just in from the Dept. of Redundancy Dept.:
    Please don’t say ” == True”. Ever.

    “os.path.isdir(d)” is both sufficient and much clearer.

  2. Jim Says:

    Hey, thanks for this post – I was staring at the “Files and Directories” part of the os module page and not seeing any functions that did anything close to what I was looking for. os.path is a winner!

    Nice one!

  3. shadwick Says:

    Similar to the vein Scott was taking, also never use “== False”. Use the “not” keyword, i.e. “if not os.path.isdir(d)”. I know you didn’t use something like this in your code, but it follows up on Scott’s comment.

  4. sandrar Says:

    Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  5. chris Says:

    Glad you like it. Hope it helped 🙂

  6. Seva S Says:

    Hi Chris,
    This was not working in Python 2.7.1
    I had to include the absolute path in order to get it to work, like so. Thank you for your post, it was helpful.

    import os, time
    dirList = os.listdir(“D:\\MyAudio\\”)
    for d in dirList:
    if os.path.isdir(“D:\\MyAudio\\”+d) == True:
    print d, “is a dir”
    else:
    print d, “is a file”

    ###results from my files below###
    1Lady_Gaga_-_Just_Dance.mp3 is a file
    Copy of Pike3.pop is a file
    Folder(2) is a dir

  7. singh Says:

    Hi
    I want to copy files from directory A to directory B
    using python script
    But if listed file is not in A then program just abort with following errors:
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/data/good_runs_mc.cedar
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/old/good_runs_mc.cedar
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/data1/good_runs_mc.cedar
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/data/good_runs_mc.cedar
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/data/bad_runs_mc.cedar
    /afs/fnal.gov/files/home/room2/venktesh/venktesh/old/bad_runs_mc.cedar
    Traceback (most recent call last):
    File “corr_runs_status.py”, line 37, in ?
    shutil.move(src, dst)
    File “/usr/lib64/python2.3/shutil.py”, line 170, in move
    copy2(src,dst)
    File “/usr/lib64/python2.3/shutil.py”, line 82, in copy2
    copyfile(src, dst)
    File “/usr/lib64/python2.3/shutil.py”, line 37, in copyfile
    fsrc = open(src, ‘rb’)
    IOError: [Errno 2] No such file or directory: ‘/afs/fnal.gov/files/home/room2/venktesh/venktesh/data/bad_runs_mc.cedar’

  8. PIyush Kumar Says:

    thanks 😀

  9. Manoj Says:

    Thanks for your blog… it helped.. 🙂 :).. Manoj

  10. Ken Says:

    Many thanks!! :):):)

  11. markus Says:

    looks like ‘C’,
    thanks Markus

  12. Techno Says:

    For newer versions of python you should use absolute path with os.path.

  13. DanB Says:

    ” == True” is fine to use. Especially if you are a beginner trying to write readable code or giving someone a tutorial.

  14. EYD Says:

    ” == True” is certainly NOT fine to use. This show a poor understanding of booleans. Writing == True (or == False ftm) is, in every case, redundant.

  15. hv Says:

    it’s not working but why that I can’t understood

  16. fiona Says:

    I have confirmed that in Python 2.7, without absolute path, it is not working.

  17. Joaquin Menchaca Says:

    This is very useful, thank you so much. The Python docs are hit or miss in usefulness. One of the basic operations for any scripting language is to interact in the environment….

  18. nursing scholarships for single mothers in maryland Says:

    Home ownership seems very not even considered for many single moms.

    They will provide advice on if they should seek a grant for paying rent, or for the mortgage.
    See whenever they work with any government programs that provide funds for single parent mortgages.
    If it were so simple, all single moms would be enjoying funding, but this isn’t the case. It is good for this reason that there happen to be grants build specifically for single parents.

  19. nc job Says:

    I do trust all of the ideas you’ve presented for your post. They are really convincing and can definitely work. Nonetheless, the posts are very brief for newbies. May you please prolong them a bit from subsequent time? Thank you for the post.

  20. Internet Money Path Work for yourself! Says:

    Hello, its fastidious article regarding media print, we all know media is a impressive source
    of data.

  21. Window Replacement Virginia Says:

    I almost nevеr drop remarks, but i did some searching and wound up here Check if an entry is a file or dirеctory in Pythοn | Look
    here first!. Аnd I actuаlly do have a couple of questions for you if you usuаlly do not mind.
    Could іt be simply me or does it sеem like a few of the comments appear likе they
    are left by bгain dead visitors? 😛 And,
    if you are posting at other onlinе sites,
    I wоuld like to follow anything new you haѵe to post.

    Coulԁ you list of all of all your social pagеs
    like youг Facebook page, twitter feed, or linkeԁin profile?

  22. slot Says:

    You’re so cool! I don’t believe I’ve truly read a single thing like this before.
    So good to find someone with a few original thoughts on this issue.

    Really.. many thanks for starting this up. This web
    site is one thing that is needed on the web,
    someone with a little originality!

  23. frank kern retired Says:

    Appreciating the commitment you put into your site and
    detailed information you offer. It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read!

    I’ve saved your site and I’m adding your RSS feeds to my Google account.

  24. corburterilio Says:

    I couldn’t resist commenting

  25. whereitallbreaksdown Says:

    for some reason, when using .exe built by pyinstaller, os.path.isdir(path) fails.
    based on the same env, the check passes when running the .py…?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: