Error while using listdir in Python

Two things:

  1. os.listdir() does not do a glob pattern matching, use the glob module for that
  2. probably you do not have a directory called '/client_side/*.*', but maybe one without the . in the name

The syntax you used works fine, if the directory you look for exists, but there is no directory called '/client_side/.'.

In addition, be careful if using Python 2.x and os.listdir, as the results on windows are different when you use u'/client_side/' and just '/client_side'.


You can do just

os.listdir('client_side')

without slashes.


This error occurs when you use os.listdir on a path which does not refer to an existing path.
For example:

>>> os.listdir('Some directory does not exist')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
WindowsError: [Error 3] : 'Some directory does not exist/*.*'

If you want to use os.listdir, you need to either guarantee the existence of the path that you would use, or use os.path.exists to check the existence first.

if os.path.exists('/client_side/'):
    do something
else:
    do something

Suppose your current working directory is c:\foobar, os.listdir('/client_side/') is equivalent to os.listdir('c:/client_side'), while os.listdir('client_side/') is equivalent to os.listdir('c:/foobar/client_side'). If your client_side directory is not in the root, such error will occur when using os.listdir.

For your 0 ouput problem, let us recall os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

and os.path.isfile(path).

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

listdir returns neither the absolute paths nor relative paths, but a list of the name of your files, while isfile requires path. Therefore, all of those names would yield False.

To obtain the path, we can either use os.path.join , concat two strings directly.

print ([name for name in os.listdir(path)
        if os.path.isfile(os.path.join(path, name))])

Or

print ([name for name in os.listdir('client_side/')
        if os.path.isfile('client_side/' + name)])

I decided to change the code into:

def numOfFiles(path):
    return len(next(os.walk(path))[2])

and use the following the call the code:

print numOfFiles("client_side")

Many thanks to everyone who told me how to pass the windows directory correctly in Python and to nrao91 in here for providing the function code.

EDIT: Thank you eryksun for correcting my code!