List files ONLY in the current directory

后端 未结 8 1870
一向
一向 2020-11-28 00:09

In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any sub directory or parent.

There do seem to be similar

相关标签:
8条回答
  • 2020-11-28 01:11

    You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

    example:

    files = os.listdir(os.curdir)  #files and directories
    

    or

    files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
    files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.
    
    0 讨论(0)
  • 2020-11-28 01:14

    You can use os.scandir(). New function in stdlib starts from Python 3.5.

    import os
    
    for entry in os.scandir('.'):
        if entry.is_file():
            print(entry.name)
    

    Faster than os.listdir(). os.walk() implements os.scandir().

    0 讨论(0)
提交回复
热议问题