Python script to list all files, directories in a given path

[root@localhost utils]# pwd
/root/Documents/dbversity/utils
[root@localhost utils]#
[root@localhost utils]#
[root@localhost utils]# ll -lhtr
total 20K
-rw-r–r–. 1 root root    0 Jun  8 14:24 _init_.py
-rw-r–r–. 1 root root   95 Jun  8 14:35 new_function.py
-rw-r–r–. 1 root root   77 Jun  8 14:54 new.py
-rw-r–r–. 1 root root  619 Jun  8 14:57 oslistdir.py
drwxr-xr-x. 3 root root 4.0K Jun  8 15:31 testdir
-rw-r–r–. 1 root root  352 Jun  8 16:02 files.py
[root@localhost utils]#
[root@localhost utils]#
[root@localhost utils]#
[root@localhost utils]# cat files.py

import os, sys
 
# Set the directory you want to start from

path = raw_input(‘Enter directory name to list all files & subdirectories :’)
print (‘You have entered \t%s’ % path)

for dirName, subdirList, fileList in os.walk(path):
    print(‘Directory Name is : %s’ % dirName)
    for fname in fileList:
        print(‘File Name is \t%s’ % fname)

[root@localhost utils]#
[root@localhost utils]# python files.py
Enter directory name to list all files & subdirectories :/root/Documents/dbversity/utils
You have entered     /root/Documents/dbversity/utils
Directory Name is : /root/Documents/dbversity/utils
File Name is     new_function.py
File Name is     oslistdir.py
File Name is     new.py
File Name is     files.py
File Name is     _init_.py
Directory Name is : /root/Documents/dbversity/utils/testdir
File Name is     newfile.txt
Directory Name is : /root/Documents/dbversity/utils/testdir/subdir
File Name is     sub_file.txt
[root@localhost utils]#

[root@localhost utils]# ll -lhtr *
-rw-r–r–. 1 root root    0 Jun  8 14:24 _init_.py
-rw-r–r–. 1 root root   95 Jun  8 14:35 new_function.py
-rw-r–r–. 1 root root   77 Jun  8 14:54 new.py
-rw-r–r–. 1 root root  619 Jun  8 14:57 oslistdir.py
-rw-r–r–. 1 root root  352 Jun  8 16:02 files.py

testdir:
total 4.0K
-rw-r–r–. 1 root root    0 Jun  8 15:18 newfile.txt
drwxr-xr-x. 2 root root 4.0K Jun  8 15:31 subdir
[root@localhost utils]#
[root@localhost utils]#
[root@localhost utils]#
[root@localhost utils]# ll -lhtr testdir/subdir/*
-rw-r–r–. 1 root root 0 Jun  8 15:31 testdir/subdir/sub_file.txt
[root@localhost utils]#
d

  • Ask Question