List files ONLY in the current directory

后端 未结 8 1869
一向
一向 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
    
    0 讨论(0)
  • 2020-11-28 01:01
    import os
    
    destdir = '/var/tmp/testdir'
    
    files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]
    
    0 讨论(0)
  • 2020-11-28 01:02

    instead of os.walk, just use os.listdir

    0 讨论(0)
  • 2020-11-28 01:02

    You can use the pathlib module.

    from pathlib import Path
    x = Path('./')
    print(list(filter(lambda y:y.is_file(), x.iterdir())))
    
    0 讨论(0)
  • 2020-11-28 01:05

    Just use os.listdir and os.path.isfile instead of os.walk.

    Example:

    import os
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    for f in files:
        # do something
    

    But be careful while applying this to other directory, like

    files = [f for f in os.listdir(somedir) if os.path.isfile(f)].
    

    which would not work because f is not a full path but relative to the current dir.

    Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))

    (Thanks Causality for the hint)

    0 讨论(0)
  • 2020-11-28 01:09

    this can be done with os.walk()

    python 3.5.2 tested;

    import os
    for root, dirs, files in os.walk('.', topdown=True):
        dirs.clear() #with topdown true, this will prevent walk from going into subs
        for file in files:
          #do some stuff
          print(file)
    

    remove the dirs.clear() line and the files in sub folders are included again.

    update with references;

    os.walk documented here and talks about the triple list being created and topdown effects.

    .clear() documented here for emptying a list

    so by clearing the relevant list from os.walk you can effect its result to your needs.

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