How to deal with " NotADirectoryError: [Errno 20] Not a directory: "

Viewed 7251

My error

---------------------------------------------------------------------------
NotADirectoryError                        Traceback (most recent call last)
<ipython-input-2-b4da6c1da6e1> in <module>
     12 lst = []
     13 for d in lst1:
---> 14     lst = lst + listdir(d)
     15 lst

<ipython-input-2-b4da6c1da6e1> in listdir(path)
      4 def listdir(path):  #传入存储的list
      5     lst = []
----> 6     for file in os.listdir(path):
      7         file_path = os.path.join(path, file)
      8         lst.append(file_path)

NotADirectoryError: [Errno 20] Not a directory: '/Users/zhangzhenzhi/Desktop/Term2_Final/CASA0006/CityofLondonCrimeData/.DS_Store'

And my code is

# -*- coding: utf-8 -*-  
import os  

def listdir(path):  #传入存储的list
    lst = []
    for file in os.listdir(path):  
        file_path = os.path.join(path, file)  
        lst.append(file_path) 
    return lst
lst1 = listdir(r'/Users/zhangzhenzhi/Desktop/Term2_Final/CASA0006/CityofLondonCrimeData' )

lst = []
for d in lst1:
    lst = lst + listdir(d)
lst

I want to save all of the files' path to a listm, but I run it, it showed an error and i can't understand what can I do?

2 Answers

You need to check type of object before "os.listdir"

def listdir(path):  #传入存储的list
    lst = []
    if os.path.isdir(path): # Check this path = path to folder
        for file in os.listdir(path):  
           file_path = os.path.join(path, file)  
           lst.append(file_path)

Look at the exception. NotADirectoryError: [Errno 20] Not a directory: '/Users/zhangzhenzhi/Desktop/Term2_Final/CASA0006/CityofLondonCrimeData/.DS_Store'

This line lst1 = listdir(r'/Users/zhangzhenzhi/Desktop/Term2_Final/CASA0006/CityofLondonCrimeData' )

This returns list of all paths including files with full path, and ".DS_Store" is a file. Then, you also loop through what you got on lst1. In which case os.listdir tries to operate on a file (the path in the traceback) which causes the exception to be thrown.

More solid way is to use package glob for that purpose. Try

glob.glob(path) and it returns the list of paths under that path. If you want it to be recursive add /** to the end of the path and add recursive=True parameter.

Related