Reputation: 4781
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:
Python2.
Upvotes: 1
Views: 2928
Reputation: 5186
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
Upvotes: 5