List only files in a directory?

后端 未结 8 1826
予麋鹿
予麋鹿 2021-02-06 21:49

Is there a way to list the files (not directories) in a directory with Python? I know I could use os.listdir and a loop of os.path.isfile()s, but if th

8条回答
  •  春和景丽
    2021-02-06 22:19

    If you use Python 3, you could use pathlib.

    But, you have to know that if you use the is_dir() method as :

    from pathlib import *
    
    #p is directory path
    #files is list of files in the form of path type
    
    files=[x for x in p.iterdir() if x.is_file()]
    

    empty files will be skipped by .iterdir()

    The solution I found is:

    from pathlib import *
    
    #p is directory path
    
    #listing all directory's content, even empty files
    contents=list(p.glob("*"))
    
    #if element in contents isn't a folder, it's a file
    #is_dir() even works for empty folders...!
    
    files=[x for x in contents if not x.is_dir()]
    

提交回复
热议问题