List only files in a directory?

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

    Using pathlib in Windows as follow:

    files = (x for x in Path("your_path") if x.is_file())

    Generates error:

    TypeError: 'WindowsPath' object is not iterable

    You should rather use Path.iterdir()

    filePath = Path("your_path")
    if filePath.is_dir():
        files = list(x for x in filePath.iterdir() if x.is_file())
    

提交回复
热议问题