List only files in a directory?

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

    Since Python 3.6 you can use glob with a recursive option "**". Note that glob will give you all files and directories, so you can keep only the ones that are files

    files = glob.glob(join(in_path, "**/*"), recursive=True)
    files = [f for f in files if os.path.isfile(f)]
    
    0 讨论(0)
  • 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):
        ...
    
    0 讨论(0)
  • 2021-02-06 22:09
    files = next(os.walk('..'))[2]
    
    0 讨论(0)
  • 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())
    
    0 讨论(0)
  • 2021-02-06 22:19

    Using pathlib, the shortest way to list only files is:

    [x for x in Path("your_path").iterdir() if x.is_file()]
    

    with depth support if need be.

    0 讨论(0)
  • 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()]
    
    0 讨论(0)
提交回复
热议问题