List only files in a directory?

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

    This is a simple generator expression:

    files = (file for file in os.listdir(path) 
             if os.path.isfile(os.path.join(path, file)))
    for file in files: # You could shorten this to one line, but it runs on a bit.
        ...
    

    Or you could make a generator function if it suited you better:

    def files(path):
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                yield file
    

    Then simply:

    for file in files(path):
        ...
    

提交回复
热议问题