I'm trying to print the name and the size of all files in a directory and all its sub-directories, but it only prints the name and size of the files in the first directory but not the sub-directories. Any help will be appreciated.
import os
path = os.getcwd()
walk_method = os.walk(path)
while True:
try:
p, sub_dir, files = next(walk_method)
break
except:
break
size_of_file = [
(f, os.stat(os.path.join(path, f)).st_size)
for f in files
]
for sub in sub_dir:
i = os.path.join(path, sub)
size = 0
for k in os.listdir(i):
size += os.stat(os.path.join(i, k)).st_size
size_of_file.append((sub, size))
for f, s in sorted(size_of_file, key = lambda x: x[1]):
print("{} : {}MB".format(os.path.join(path, f), round(s/(1024*1024), 3)))
I'm expecting to print the name and file size of all files in the current directory and all the sub-directories.