318

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 solutions out there, but they don't seem to work for me. Here's my code snippet:

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

Let's suppose I have 2 files, holygrail.py and Tim inside my current directory. I have a folder as well and it contains two files - let's call them Arthur and Lancelot - inside it. When I run the script, this is what I get:

holygrail.py
Tim
Arthur
Lancelot

I am happy with holygrail.py and Tim. But the two files, Arthur and Lancelot, I do not want listed.

realmanusharma
  • 330
  • 2
  • 10
slam_duncan
  • 3,478
  • 2
  • 18
  • 18

10 Answers10

529

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 directory.

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

(Thanks Causality for the hint)

Melike
  • 468
  • 1
  • 7
  • 15
sloth
  • 99,095
  • 21
  • 171
  • 219
  • 9
    This is what I needed in the end `[os.path.join(path_base,f) for f in os.listdir(path_base) if os.path.isfile(os.path.join(path_base,f))]` – citynorman Jan 05 '18 at 18:55
  • 5
    This is his answer: `files = [f for f in os.listdir("/somedir") if os.path.isfile(os.path.join("/somedir", f))]'` – Jeff Luyet Jul 09 '19 at 18:03
90

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.
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I think the filter version only works if it's curdir. E.g. it won't work for files = filter(os.path.isfile, os.listdir(anyFolderPath))? – Paul Sumpner Aug 09 '20 at 13:46
30
import os

destdir = '/var/tmp/testdir'

files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]
Max Truxa
  • 3,308
  • 25
  • 38
19

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().

prasastoadi
  • 2,536
  • 2
  • 16
  • 14
15

You can use the pathlib module.

from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))
Flimm
  • 136,138
  • 45
  • 251
  • 267
Pygirl
  • 12,969
  • 5
  • 30
  • 43
  • This is really useful when using pathlib.Path. Usually I use pathlib.Path. Thank you very much. – Uzzal Podder Jul 09 '20 at 12:07
  • 1
    using the `os` module covered in older solutions is fine, but starting to incorporate easier to use modules like `glob` and `pathlib` should be emphasized. – Austin A Jan 28 '21 at 04:47
7

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.

2114L3
  • 564
  • 5
  • 8
5
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
Ozgur Oz
  • 740
  • 6
  • 9
3

instead of os.walk, just use os.listdir

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
1

Following up on Pygirl and Flimm, use of pathlib, (really helpful reference, btw) their solution included the full path in the result, so here is a solution that outputs just the file names:

from pathlib import Path
p = Path(destination_dir) # destination_dir = './' in original post
files = [x.name for x in p.iterdir() if x.is_file()]
print(files)
0

To list files in a specific folder excluding files in its sub-folders with os.walk use:

_, _, file_list = next(os.walk(data_folder))
Nir
  • 1,618
  • 16
  • 24