SSK :
i am trying to list directories, sub-directories files by the time modified order. i am getting desired result with below code. But when put this code in function, i am getting only last line.
import os
from fnmatch import fnmatch
root = 'Test\\inputs\\'
pattern = "*"
for path, subdirs, files in sorted(os.walk(root), reverse=True):
for name in files:
if fnmatch(name, pattern):
print(os.path.join(path, name))
Output:
Test\inputs\backup\cdr_dsw
Test\inputs\backup\cdr_ds.xml
Test\inputs\backup\dsdf.xml
Test\inputs\testing.txt
same code using function:
import os
from fnmatch import fnmatch
root = 'Test\\inputs\\'
pattern = "*"
def Listdir():
X = []
for path, subdirs, files in sorted(os.walk(root), reverse=True):
for name in files:
if fnmatch(name, pattern):
X.append(os.path.join(path, name))
return X
print(Listdir())
output:
Test\inputs\backup\cdr_dsw
Not sure what mistake i am doing. please help to correct my mistake. i want to use this as a function.
thanks in advance.
Ali Rn :
because you write the return X
into the if
, it just return the first one , you can write it under the for
, so you can return the X when all your path appended
def Listdir():
X = []
for path, subdirs, files in sorted(os.walk(root), reverse=True):
for name in files:
if fnmatch(name, pattern):
X.append(os.path.join(path, name))
return X
print(Listdir())