Copy and paste code for those who want to deep walk all nested sub directories:
- using python's
recursion call
with os.listdir()
:
import os
count = 0
def deep_walk(mypath):
global count
for file in os.listdir(mypath):
file_path = os.path.join(mypath, file)
if os.path.isdir(file_path):
deep_walk(file_path)
else:
count += 1
print(file_path)
mypath="/tmp"
deep_walk(mypath)
print(f"Total file count: {count}")
- using python's standard library
os.walk()
:
import os
def walk_dir(mypath):
count = 0
for root, dirs, files in os.walk(mypath):
for file in files:
file_path = os.path.join(root, file)
count += 1
print(file_path)
print(f"Total file count: {count}")
mypath = "/tmp"
walk_dir(mypath)
The difference is that with os.walk()
you won't need to walk every directories of each sub directories mannually, the library will do it for you, no matter how many nested directories you have.
from x import *
. That's one piece of advice for Pythonic style. – Affidavitfiles.append(item)
or multiple items withfiles.extend([item1, item2, ...])
– Blakemore