Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Data Science by (18.4k points)

I have a folder that contains a few files of different types (.cpp, .hpp, .ipp ...) and in that folder are multiple sub-folders that also contain these different file types. My question is, is there a single loop that I can make that will search the first main folder and return a list full of all the .cpp files from either folder? So far, I know that:

folder_list = [f for f in os.listdir(os.getcwd()) if os.path.isdir(f)]

will return a list of the sub-folders, and then I can change the working directory and get the files list to append.

I also know that:

file_list = [f for f in listdir(os.getcwd()) if isfile(join(os.getcwd(), f))]

will return a list of the files.

However, I won't know the names of these sub-folders (and therefore the directory) beforehand. Thank you for any help

1 Answer

0 votes
by (36.8k points)

Using listdir and endswith, you can do this. This will help you identify the characters coming at the end of a string:

filetypes = ['cpp', 'hpp', 'ipp']

dir = "target directory"

files = [[f for f in os.listdir(dir) if f.endswith(type_)] for type_ in filetypes]

This will result in a list of lists where each list will hold files of a specific type.

Do check out Data Science with Python course which helps you understand from scratch

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...