Cemre Mengü
Cemre Mengü

Reputation: 18754

Following a nested directory structure until the end

I have a some directories that contain some other directories which, at the lowest level, contain bunch of csv files such as (folder) a -> b -> c -> (csv files). There is usually only one folder at each level. When I process a directory how can I follow this structure until the end to get the csv files ? I was thinking maybe a recursive solution but I think there may be better ways to do this. I am using python. Hope I was clear.

Upvotes: 1

Views: 248

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159875

The os package has a walk function that will do exactly what you need:

for current_path, directory, files in walk("/some/path"):
    # current_path is the full path of the directory we are currently in
    # directory is the name of the directory
    # files is a list of file names in this directory

You can use os.path's to derive the full path to each file (if you need it).

Alternately, you might find the glob module to be of more use to you:

for csv_file in glob(/some/path/*/*.csv"):
    # csv_file is the full path to the csv file.

Upvotes: 3

Related Questions