I was working on a project to list all files and directories and their recursive elements from a path, code of the function:
def recursive_search(path: str) -> "list[str]":
"""get all files from an absolute path
:param path: absolute path of the directory to search
:type path: str
:return: a list of all files
:rtype: list[str]
"""
found_files = []
if not os.path.isdir(path):
raise RuntimeError(f"'{path}' is not a directory")
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isfile(full_path):
found_files.append(full_path)
elif os.path.isdir(full_path):
found_files.extend(recursive_search(full_path))
return found_files
I call the function like this:
if __name__ == '__main__':
user = getuser()
directory = "C:\\Users\\" user "\\Desktop\\archivos"
path = (recursive_search(directory))
Its possible ignore a file, for example I want to get all directories and files from "C:\Users\XXX\Desktop", but I don't want to catch the file "C:\Users\XXX\Desktop\desktop.ini", how I can do this?
Thanks.
CodePudding user response:
I believe it should be straight-forward here with your example. You can improve it further to get a relative path.
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isfile(full_path):
if not os.path.samefile(full_path, 'C:\\Users\\XXX\\Desktop\\desktop.ini'):
found_files.append(full_path)
elif os.path.isdir(full_path):
found_files.extend(recursive_search(full_path))
return found_files