Skip to content
Advertisement

Print number of occurrences of any items in a list in paths

I am using os.walk to identify paths in a generic source directory (SRC) that contain any strings in my_list:

JavaScript

And let’s say that print(source_path) gives the following:

JavaScript

My goal is to shutil.move my source_path’s, but since, for example, moving /User/dir_1/bird_files/ and then trying to move /User/dir_1/bird_files/bird_a_files/ will result in a FileNotFound Error, I want to filter my source_path’s to include those with only 1 occurrence of any string in my_list, such that my source_path’s are:

JavaScript

I have tried source_path.count(x) == 1, but that iterates through my_list as opposed to counting any x in my_list, such that my output is (for example):

JavaScript

but I want to see (for example):

JavaScript

Which would allow me to filter out any source_path with count != 1

Advertisement

Answer

Use a comprehension to filter by count, then sum the result (True is cast to 1) to get the “any” behavior.

JavaScript

Output

JavaScript

EDIT: From the comment, a os.walk approach.

Idea: remove terms from the dirnames parameter

Remark: I used as filtering condition (see comment in the code) the method substring is contained in string which is quite poor. In this special case a more robust one could be d.startswith(c). For more flexibility use a regex-like solution.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement