I'm trying to get the list of files in a particular directory and count the number of files in the directory. I always get the following error:
WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'
My code is:
print len([name for name in os.listdir('/client_side/') if os.path.isfile(name)])
I followed the code example given here.
I am running the Python script on Pyscripter and the directory /client_side/ do exists. My python code is in the root folder and has a sub-folder called "client_side". Can someone help me out on this?
You want:
with a "." before "/client_side/".
The dot means the current path where you are working (i.e. from where you are calling your code), so "./client_side/" represents the path you want, which is specified relatively to your current directory.
If you write only "/client_side/", in unix, the program would look for a folder in the root of the system, instead of the folder that you want.
As I can see a
WindowsError
, Just wondering if this has something to do with the '/' in windows ! Ideally, on windows, you should have something likeos.path.join('C:','client_side')
Checking for existence is subject to a race. Better to handle the error (beg forgiveness instead of ask permission). Plus, in Python 3 you can suppress errors. Use suppress from contextlib:
I decided to change the code into:
and use the following the call the code:
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!
Two things:
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'.
This error occurs when you use
os.listdir
on a path which does not refer to an existing path.For example:
If you want to use
os.listdir
, you need to either guarantee the existence of the path that you would use, or useos.path.exists
to check the existence first.Suppose your current working directory is
c:\foobar
,os.listdir('/client_side/')
is equivalent toos.listdir('c:/client_side')
, whileos.listdir('client_side/')
is equivalent toos.listdir('c:/foobar/client_side')
. If your client_side directory is not in the root, such error will occur when usingos.listdir
.For your 0 ouput problem, let us recall
os.listdir(path)
and
os.path.isfile(path)
.listdir
returns neither the absolute paths nor relative paths, but a list of the name of your files, whileisfile
requires path. Therefore, all of those names would yieldFalse
.To obtain the path, we can either use
os.path.join
, concat two strings directly.Or