Error while using listdir in Python

2020-01-29 09:47发布

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?

8条回答
贼婆χ
2楼-- · 2020-01-29 10:48

If you just want to see all the files in the directory where your script is located, you can use os.path.dirname(sys.argv[0]). This will give the path of the directory where your script is.

Then, with fnmatch function you can obtain the list of files in that directory with a name and/or extension specified in the filenamevariable.

import os,sys
from fnmatch import fnmatch

directory = os.path.dirname(sys.argv[0])    #this determines the directory
file_name= "*"                              #if you want the python files only, change "*" to "*.py"

for path, subdirs, files in os.walk(directory):
    for name in files:
        if fnmatch(name, file_name):
            print (os.path.join(path, name))

I hope this helps.

查看更多
Fickle 薄情
3楼-- · 2020-01-29 10:49

You can do just

os.listdir('client_side')

without slashes.

查看更多
登录 后发表回答