List only files in a directory?

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

    For the special case of working with files in the current directory, you could do it as a simple one-liner list comprehension:

    [f for f in os.listdir(os.curdir) if os.path.isfile(f)]
    

    Otherwise in the more general case, directory paths & filenames have to be joined:

    dirpath = '~/path_to_dir_of_interest'
    files = [f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, f))]
    

提交回复
热议问题