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

后端 未结 6 1986
醉酒成梦
醉酒成梦 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 12:23

    pathlib, that is new in v. 3.4, makes like easier. The line labelled 1 makes a non-recursive list of the current folder, the one labelled 2 the recursive list.

    from pathlib import Path
    
    import os
    os.chdir('c:/utilities')
    
    print (len(list(Path('.').glob('*')))) ## 1
    print (len(list(Path('.').glob('**/*')))) ## 2
    

    There are more goodies too. With these additional lines you can see both the absolute and relative file names for those items that are files.

    for item in Path('.').glob('*'):
        if item.is_file():
            print (str(item), str(item.absolute()))
    

    Result:

    boxee.py c:\utilities\boxee.py
    boxee_user_catalog.sqlite c:\utilities\boxee_user_catalog.sqlite
    find RSS.py c:\utilities\find RSS.py
    MyVideos34.sqlite c:\utilities\MyVideos34.sqlite
    newsletter-1 c:\utilities\newsletter-1
    notes.txt c:\utilities\notes.txt
    README c:\utilities\README
    saveHighlighted.ahk c:\utilities\saveHighlighted.ahk
    saveHighlighted.ahk.bak c:\utilities\saveHighlighted.ahk.bak
    temp.htm c:\utilities\temp.htm
    to_csv.py c:\utilities\to_csv.py
    

提交回复
热议问题