Error while using listdir in Python

后端 未结 8 941
小蘑菇
小蘑菇 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

    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)
    

提交回复
热议问题