Counting Files in Directory

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghostxx
    New Member
    • Oct 2009
    • 4

    Counting Files in Directory

    Alright well i've been working at this for a ridiculously longer amount of time than i think i should have been, so i finally gave up and that's why im here. I program in C++ and hardly do any python.. ever. So i need a little help and hope you all will be kind enough to throw some knowledge my way.

    What i need to do, is count the files in the directory that my python script is currently in. It needs to be able to list ONLY the files, and NO sub directories that may be in that directory itself.

    I've been looking at this thread: http://bytes.com/topic/python/answer...iles-directory and have been trying variations of tons of the solutions on this page, but continue to get errors. Im also trying to use the os.walk function, but it seems that everytime i run my script it works, but it does not display any output of the number of files in the directory. I even used the raw_input() function to see if it was just a matter of keeping the script open to see any output, but even so... the output was blank and all i had was the raw_input() message to quit.

    So, any help/solutions would be greatly appreciated. Thanks so much.
    Last edited by bvdet; Oct 7 '09, 02:13 PM. Reason: Fix link
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    It's much easier than you might think. These two functions can do the work for you: os.listdir() and os.path.isfile( ).
    Code:
    >>> def filecount(dir_name):
    ... 	return len([f for f in os.listdir(dir_name) if os.path.isfile(f)])
    ... 
    >>> filecount(os.getcwd())
    97
    >>>

    Comment

    • ghostxx
      New Member
      • Oct 2009
      • 4

      #3
      Ok, i used that code you gave me and when i run the script, it works, but still does not display the number of files in the directory. When i do "python example.py" it executes and then directly moves on to the command line. I used raw_input() again to see if anything else was there, but still no output. :(

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Module os must be imported.
        Code:
        import os
        I write all much of my code in PythonWin, a Python editor available in pywin32. The code in my post was typed into the Interactive Window. There are many Python editors and IDEs available, some of them free.

        You do not need to initialize variable dir_name before the function definition.

        The 97 is the number of files in my current working directory (os.path.getcwd( )).

        -BV

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Try this:
          Code:
          print filecount("your_directory")

          Comment

          • ghostxx
            New Member
            • Oct 2009
            • 4

            #6
            Alright i got it. And its working perfectly now. Thanks so much bvdet.

            Last question though. How can i make it so i can do something like this: "There are",_, "files in this directory." And make it so that the ,_, will display the number of files in the directory. I know that is the correct code right there, but i don't know what would replace the _ in the ,_, ?? How can i go about doing this?

            Comment

            • ghostxx
              New Member
              • Oct 2009
              • 4

              #7
              Ha! I figured it out!

              I just did it like this lol: print "There are",filecount( path), "files in this directory." and it worked lol.

              Thanks for all the help bvdet. Could not have done it without your help.

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                If I were to write a script, it would look something like this:
                Code:
                import os
                
                def filecount(dir_name):
                    # return the number of files in directory dir_name
                    try:
                        return len([f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))])
                    except Exception, e:
                        return None
                
                if __name__ == '__main__':
                    the_path = raw_input("Enter directory path")
                    n = filecount(the_path)
                    if n is None:
                        print "Invalid directory name."
                    else:
                        print "The number of files in directory %s: %d" % (the_path, n)
                Edit:
                Good work - you answered your own question! I am glad I could help.

                -BV

                Comment

                • plotdevice
                  New Member
                  • May 2010
                  • 3

                  #9
                  Sorry for the thread necromancy, but I am in almost exactly the same situation as the OP. These solutions are not working for me. I don't know if it's because I'm having a brain eclipse, or what.

                  This:
                  Code:
                  len([f for f in os.listdir('.') if os.path.isfile(f)])
                  returns the correct number of files for the working directory. However,

                  Code:
                  where_to_look = '/home/user/files'
                  len([f for f in os.listdir(where_to_look) if os.path.isfile(f)])
                  always returns 0, and I have no idea why.

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    Originally posted by plotdevice
                    Sorry for the thread necromancy, but I am in almost exactly the same situation as the OP. These solutions are not working for me. I don't know if it's because I'm having a brain eclipse, or what.

                    This:
                    Code:
                    len([f for f in os.listdir('.') if os.path.isfile(f)])
                    returns the correct number of files for the working directory. However,

                    Code:
                    where_to_look = '/home/user/files'
                    len([f for f in os.listdir(where_to_look) if os.path.isfile(f)])
                    always returns 0, and I have no idea why.
                    You are omitting an important part.
                    Code:
                    where_to_look = '/home/user/files'
                    len([f for f in os.listdir(where_to_look) if os.path.isfile(os.path.join(where_to_look, f))])

                    Comment

                    • plotdevice
                      New Member
                      • May 2010
                      • 3

                      #11
                      Originally posted by bvdet
                      You are omitting an important part.
                      Code:
                      where_to_look = '/home/user/files'
                      len([f for f in os.listdir(where_to_look) if os.path.isfile(os.path.join(where_to_look, f))])
                      gah! Thanks.

                      Comment

                      • new to python
                        New Member
                        • Jul 2010
                        • 4

                        #12
                        can you please explain how this line works. i want to understand it


                        Code:
                        len([f for f in os.listdir(where_to_look) if os.path.isfile(os.path.join(where_to_look, f))])

                        Comment

                        • bvdet
                          Recognized Expert Specialist
                          • Oct 2006
                          • 2851

                          #13
                          Code:
                          len([f for f in os.listdir(where_to_look) if os.path.isfile(os.path.join(where_to_look, f))])
                          len(s) returns the number of elements in a sequence.

                          The argument is a list comprehension. Here's a decent explanation of a list comprehension.
                          You can do the same thing with a for loop:
                          Code:
                          >>> import os
                          >>> fileList = []
                          >>> where_to_look = "G:\\"
                          >>> for f in os.listdir(where_to_look):
                          ... 	if os.path.isfile(os.path.join(where_to_look, f)):
                          ... 		fileList.append(f)
                          ... 		
                          >>> len(fileList)
                          5
                          >>>

                          Comment

                          • new to python
                            New Member
                            • Jul 2010
                            • 4

                            #14
                            thank you so much for your help, but im still confused about one line.

                            Code:
                            if os.path.isfile(os.path.join(where_to_look, f)):
                            the begining of the line is just to check if its a file but what does os.path.join do? and why does it take two inputs?

                            Comment

                            • bvdet
                              Recognized Expert Specialist
                              • Oct 2006
                              • 2851

                              #15
                              os.listdir() returns a list of directory entry names. In order to check if the names are associated with file objects, you must determine the the full path to each name if the entries are not in the current working directory. os.path.join() returns the path and named joined to pass to os.path.isfile( ).

                              Comment

                              Working...