1

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?

  • Add some example code – null_override Jun 19 '20 at 04:19
  • You seems to get the logic, to check if the path is file or directory use `os.path.isfile()` and `os.path.isdir()` https://docs.python.org/3/library/os.path.html#os.path.isfile. To iterate over a folder check this [answer](https://stackoverflow.com/a/19587581/11225821) – Linh Nguyen Jun 19 '20 at 04:21

3 Answers3

1

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)
0

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)
Rajith Thennakoon
  • 3,975
  • 2
  • 14
  • 24
0

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)
adamkgray
  • 1,717
  • 1
  • 10
  • 26