How do I read the number of files in a folder using Python?

后端 未结 6 1997
醉酒成梦
醉酒成梦 2021-02-07 11:56

How do I read the number of files in a specific folder using Python? Example code would be awesome!

6条回答
  •  渐次进展
    2021-02-07 12:29

    Mark Byer's answer is simple, elegant, and goes along with the python spirit.

    There's a problem, however: if you try to run that for any other directory than ".", it will fail, since os.listdir() returns the names of the files, not the full path. Those two are the same when listing the current working directory, so the error goes undetected in the source above.

    For example, if your at "/home/me" and you list "/tmp", you'll get (say) ['flashXVA67']. You'll be testing "/home/me/flashXVA67" instead of "/tmp/flashXVA67" with the method above.

    You can fix this using os.path.join(), like this:

    import os.path
    path = './whatever'
    count = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
    

    Also, if you're going to be doing this count a lot and require performance, you may want to do it without generating additional lists. Here's a less elegant, unpythonesque yet efficient solution:

    import os
    
    def fcount(path):
        """ Counts the number of files in a directory """
        count = 0
        for f in os.listdir(path):
            if os.path.isfile(os.path.join(path, f)):
                count += 1
    
        return count
    
    
    # The following line prints the number of files in the current directory:
    path = "./whatever"
    print fcount(path)
    

提交回复
热议问题