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

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

    To count files and directories non-recursively you can use os.listdir and take its length.

    To count files and directories recursively you can use os.walk to iterate over the files and subdirectories in the directory.

    If you only want to count files not directories you can use os.listdir and os.path.file to check if each entry is a file:

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

    Or alternatively using a generator:

    num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path))
    

    Or you can use os.walk as follows:

    len(os.walk(path).next()[2])
    

    I found some of these ideas from this thread.

提交回复
热议问题