Home > Back-end >  How do i get a loop to read through subdirectorys and list files then go back to the directory i was
How do i get a loop to read through subdirectorys and list files then go back to the directory i was

Time:05-22

I'm trying to find out how to list files in a subdirectory the return to the directory I was working in and continue finding files

#!home/usr/env python3 import os files = [] pather = os.path while : for file in os.listdir(): if file == "for.py" or file.startswith("."): continue files.append(file) while os.path.isdir(file) == "True": os.chdir(file) if os.pathisfile(file): files.append(file)

print(files)

That's my code so far

If you could please help that would be amazing

CodePudding user response:

This should work:

import os
files = [os.path.join(path, name).replace(os.getcwd(), "") for path, subdirs, files in os.walk(os.getcwd()) for name in files]
  • Related