1

Is exist some usual way to enumerate all files (and optionally folders, optionally recursive with sub dirs) inside a given folder? So I pass a folder path and get list of resulting full paths.

If you show how to exclude all read-only and all hidden files from this result, it'd be better. So input params:

  • dir: full path of a folder
  • option_dirs: include dirs paths to listing
  • option_subdirs: process also all subdirs of dir
  • option_no_ro: exclude read-only files
  • option_no_hid: exclude hidden files

Python2.

Prog1020
  • 4,530
  • 8
  • 31
  • 65
  • 3
    possible duplicate of [how to list all files of a directory in python](http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python) – ecatmur Jul 22 '13 at 21:42
  • Link shows answer for 1) and 2) options. But how to exclude RO and Hidden files? – Prog1020 Jul 22 '13 at 22:03

1 Answers1

5

You should probably look into os.walk and os.access.

For the actual implementation you can do something like:

import os

def get_files(path, option_dirs, option_subdirs, option_no_ro, option_no_hid):
    outfiles = []
    for root, dirs, files in os.walk(path):
        if option_no_hid:
            # In linux, hidden files start with .
            files = [ f for f in files if not f.startswith('.') ]
        if option_no_ro:
            # Use os.path.access to check if the file is readable
            # We have to use os.path.join(root, f) to get the full path
            files = [ f for f in files if os.access(os.path.join(root, f), os.R_OK) ]
        if option_dirs:
            # Use os.path.join again
            outfiles.extend([ os.path.join(root, f) for f in files ])
        else:
            outfiles.extend(files)
        if not option_subdirs:
            # If we don't want to get subdirs, then we just exit the first
            # time through the for loop
            return outfiles
    return outfiles
mr2ert
  • 5,146
  • 1
  • 21
  • 32