List files ONLY in the current directory

后端 未结 8 1934
一向
一向 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 00:57

    import os
    for subdir, dirs, files in os.walk('./'):
        for file in files:
          do some stuff
          print file
    

    You can improve this code with del dirs[:]which will be like following .

    import os
    for subdir, dirs, files in os.walk('./'):
        del dirs[:]
        for file in files:
          do some stuff
          print file
    

    Or even better if you could point os.walk with current working directory .

    import os
    cwd = os.getcwd()
    for subdir, dirs, files in os.walk(cwd, topdown=True):
        del dirs[:]  # remove the sub directories.
        for file in files:
          do some stuff
          print file
    

提交回复
热议问题