<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > Today comes across a pit, a python list problem that often comes out of your most familiar places, especially in small places, the problem: I want to list all the next levels of files and subdirectories in the directory (in the case of directories and files that contain only the next level of directories, not directories), and then get only the current subdirectory. The problem description is very clear, very easy to write a function, is not os.listdir (path), yes, that is, this feature can be listed in the next level of all directories and files, return results in a list, then our main work of the general idea is to filter this result list? Good, the OS also has the related function, Os.path.isfile (filepath), can judge the file is not a file, is a file, that is removed from the list, processing, is the final result list we want, is this it? The idea is perfect, the reality is very cruel, very unexpected, this is uncertain. We experiment with code:</span>
Import osdef count_subdir (src): listall = Os.listdir (src) for line in Listall: filepath = os.path.join (SRC, Line) if Os.path.isfile (filepath): listall.remove (line) return listall if __name__ = = "__main__": src = R ' f:\src ' ret = count_subdir (src) for line in RET: print Line
Output Result:
Look at the end ... There are still files, and we compare the list of the original results that were not processed:
The Final Document project, can be compared, is not found what the law ... The other one is missing one ...
Then why does this happen? Just because of the problem with the for-Loop and List.remove () method, let's go through the process, and the problem is exposed.
Let's go again: first for loop, one line per loop, if this line is file, delete from list, then second loop .... The question has come, is not missing what? After deletion, are there any other actions that are not shown in code? The answer is yes,
def count_subdir (SRC): listdir = [] listall = os.listdir (src) for line in listall: filepath = Os.path.join (src,line) if Os.path.isdir (filepath): listdir.append (filepath) return Listdir
The output is:
OK, this time it's really complete, it's a real catalogue .... I can't believe it, I didn't find a problem at first, I always felt no problem ... Do not analyze the results and really put the end of the Remove method to the missing out ... I think a lot of people just know remove the removal of this step, did not think of the list after deletion adjustment, haha!
Remove from the list of missing Python search lists