List files ONLY in the current directory List files ONLY in the current directory python python

List files ONLY in the current directory


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

Example:

import osfiles = [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)


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 onlyfiles = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.


import osdestdir = '/var/tmp/testdir'files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]