aastha thapaliya
aastha thapaliya

Reputation: 23

Is there an efficient way to recurse in a directory?

I want to perform:

  1. iterate over the content of the folder

  2. if content is file, append to list

  3. if content is folder, goto 1

  4. if folder name is "depth" or "ir", ignore

I am using python. Can you help?

Upvotes: 1

Views: 92

Answers (3)

aastha thapaliya
aastha thapaliya

Reputation: 23

ended up doing something like:

_files = []
dir = "path/to/folder"
for root, dirs, files in os.walk(dir, topdown=False):
    for name in files:
        files = os.path.join(root, name)
        if root.split("/")[-1] in ["depth", "ir"]:
            continue
        _files.append(files)
 print(_files)

Upvotes: 1

adamkgray
adamkgray

Reputation: 1947

The os.walk() will recurse for you.

import os
res = []
for (root, dirs, files) in os.walk('/path/to/dir'):
    # root is the absolute path to the dir, so check if the last part is depth or ir
    if root.split("/")[-1] in ["depth", "ir"]:
        continue
    else:
        # files is a list of files
        res.extend(files)

print(res)

Upvotes: 0

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

Try this

import os
basepath ="<path>" 
files=[]
def loopover(path):
    contents = os.listdir(path)
    for c in contents:
        d = os.path.join(path,c)
        if os.path.isfile(d):
            files.append(c)
        if os.path.isdir(d):
            if (c=="depth" or c=="ir"):
                continue
            else:
                loopover(d)

loopover(basepath)

Upvotes: 0

Related Questions