I have a big folder in which there are many subfolders. Each of those subfolders can also have some subfolders ( number can be different ) in it. This goes on for some levels. And in the end, there is a text file. How can I make a python program that traverses the entire directory as deep as it goes and prints the name of the text file? In simpler terms, I want to navigate through the directory as long as there are no more sub-directories?
Asked
Active
Viewed 427 times
0
-
2Does this answer your question? [How do you walk through the directories using python?](https://stackoverflow.com/questions/2922783/how-do-you-walk-through-the-directories-using-python) – funie200 Oct 22 '20 at 11:41
1 Answers
3
Use os.walk
.
For instance, creating a deep hierarchy like
$ mkdir -p a/b/c/d/e/f/g
$ touch a/b/c/d/e/f/g/h.txt
and running
import os
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
filepath = os.path.join(dirname, filename)
print(filepath)
yields
./a/b/c/d/e/f/g/h.txt
– do what you will with filepath
.
Another option, if you're using Python 3.5 or newer (and you probably should be) is glob.glob()
with a recursive pattern:
>>> print(glob.glob("./**/*.txt", recursive=True))
['./a/b/c/d/e/f/g/h.txt']

AKX
- 152,115
- 15
- 115
- 172