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

后端 未结 6 1983
醉酒成梦
醉酒成梦 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:24

    You can use the glob module:

    >>> import glob
    >>> print len(glob.glob('/tmp/*'))
    10
    

    Or, as Mark Byers suggests in his answer, if you only want files:

    >>> print [f for f in glob.glob('/tmp/*') if os.path.isfile(f)]
    ['/tmp/foo']
    >>> print sum(os.path.isfile(f) for f in glob.glob('/tmp/*'))
    1
    

提交回复
热议问题