os.walk without altering file arrangement

Viewed 31

I am looping through subfolders within a folder using os.walk. I am trying to grab the names of the files within the subfolders. The code works but the issue is it is not printing them the way the files are arranged in my local pc

import os
r=[]
def list_file(dir):
  for root, dirs, files in os.walk(dir):
    for name in files:
        r.append(name)
return r

list_file(folder)

for the first subfolder, I was expecting an arrangement of 153, 154, 157, 158, 159, 160, 249, 250, 298, 302, 308, 357, 361, 376, 377, 380, 472, 473, 562, 755, 925, 926, 1078, 1079, 1080, 1081 but I got 1078, 1079, 1080, 1081 first followed by the rest. How do I ensure the arrangement isnt altered.

1 Answers
import os
from natsort import natsorted

def list_files1(dir):
r = []
for root, dirs, files in os.walk(dir):
    j=natsorted(files)
    r.extend(os.path.splitext(name)[0] for name in j)
return r
Related