List only files in a directory?

后端 未结 8 1789
予麋鹿
予麋鹿 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:24

    You could try pathlib, which has a lot of other useful stuff too.

    Pathlib is an object-oriented library for interacting with filesystem paths. To get the files in the current directory, one can do:

    from pathlib import *
    files = (x for x in Path(".") if x.is_file())
    for file in files:
        print(str(file), "is a file!")
    

    This is, in my opinion, more Pythonic than using os.path.

    See also: PEP 428.

提交回复
热议问题