Error while using listdir in Python

后端 未结 8 839
小蘑菇
小蘑菇 2020-12-10 04:14

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         


        
相关标签:
8条回答
  • 2020-12-10 04:54

    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!

    0 讨论(0)
  • 2020-12-10 04:54

    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:

     with suppress(FileNotFoundError):
         for name in os.listdir('foo'):
             print(name)
    
    0 讨论(0)
  • 2020-12-10 04:56

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

    0 讨论(0)
  • 2020-12-10 04:56

    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 like os.path.join('C:','client_side')

    0 讨论(0)
  • 2020-12-10 05:05

    You can do just

    os.listdir('client_side')
    

    without slashes.

    0 讨论(0)
  • 2020-12-10 05:06

    You want:

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

    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.

    0 讨论(0)
提交回复
热议问题