i have directory path/to/dir
that contains 10 subdirectories. there files in all of the subdirectories. I want to append these files in every subdirectory into a unique list.
How can I do this?
Asked
Active
Viewed 69 times
0

Mo.be
- 95
- 2
- 11
-
Does this answer your question? [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – Faraaz Kurawle Mar 23 '22 at 09:38
3 Answers
3
What i understood is you just wanted to list all the filenames from a particular directory and its sub-directory.
list1=[] #Empty list
for root, dirs, files in os.walk(fr"path\\to\\directory", topdown=False):
#Listing Directory
for name in files:
a=os.path.join(root, name)
print(a)
list1.append(a)

Faraaz Kurawle
- 1,085
- 6
- 24
2
import os
path="C://Users//<user_name>//Desktop"
obj = os.scandir()
print("Files and Directories in '% s':" % path)
for entry in obj:
if entry.is_dir() or entry.is_file():
print(entry.name)
For listing whole directory:
import os
def list_dirs(path):
obj = os.scandir(path)
for entry in obj:
if entry.is_dir():
print(1,entry.path)
list_dirs(entry)
elif entry.is_file():
print(2,entry.name)
else:
break
list_dirs(path)
It basically use's os.scandir
method which provides both speed and more benefit like file meta data ect, with recursion to obtain list of whole directory.
also a list comprehension method for @FaraazKurawle 's answer:
def list_dir(path):
path=fr"{path}"
list_1=[os.path.join(root, name) for root, dirs, files in os.walk(path, topdown=False) for name in files]
return list_1
some helpful links:

Binge Programming
- 46
- 5
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 22 '22 at 15:32
1
import glob
path = '\\path\\to\\dir\\'
files = [f for f in glob.glob(path + "**/*", recursive=True)]

DDaly
- 474
- 2
- 6