Search This Blog

Monday, September 28, 2015

Directory Navigation in python - Script

import os,re,shutil,fnmatch

ex_path="D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob"

# Clean up
if not os.path.exists(ex_path):
    os.mkdir(ex_path)
else:
    shutil.rmtree(ex_path)
    os.mkdir(ex_path)

os.chdir(ex_path)

# Pre-Requisites
dir_list=[]

for i in range(0,4):
    dir_name="dir_%d" %i
    os.mkdir(dir_name)
    dir_list.append([dir_name])

for directory in dir_list:
    print directory[0]
    dir_path=ex_path+"\\" + directory[0]
    print dir_path
    os.chdir(dir_path)
    for i in range(0,4):
        fdesc=open("file_%s_%s" %(directory[0],i),"w")
        fdesc.close()
 
os.mkdir("sub_directory")
change_path=ex_path+"\dir_3\sub_directory"
print change_path
os.chdir(change_path)
fdesc=open("subdirectory.txt","w")
fdesc.close()

for dirpath, dirs, files in os.walk(ex_path):
    path = dirpath.split("\\")
    print len(path)
    print '|',(len(path))*'---','[',os.path.basename(dirpath),']'
    for f in files:
        print "|",(len(path))*'---',f

     
OUTPUT: ======= >>> ================================ RESTART ================================ >>> dir_0 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_0 dir_1 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_1 dir_2 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_2 dir_3 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_3 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_3\sub_directory 6 | ------------------ [ Glob ] 7 | --------------------- [ dir_0 ] | --------------------- file_dir_0_0 | --------------------- file_dir_0_1 | --------------------- file_dir_0_2 | --------------------- file_dir_0_3 7 | --------------------- [ dir_1 ] | --------------------- file_dir_1_0 | --------------------- file_dir_1_1 | --------------------- file_dir_1_2 | --------------------- file_dir_1_3 7 | --------------------- [ dir_2 ] | --------------------- file_dir_2_0 | --------------------- file_dir_2_1 | --------------------- file_dir_2_2 | --------------------- file_dir_2_3 7 | --------------------- [ dir_3 ] | --------------------- file_dir_3_0 | --------------------- file_dir_3_1 | --------------------- file_dir_3_2 | --------------------- file_dir_3_3 8 | ------------------------ [ sub_directory ] | ------------------------ subdirectory.txt >>> >>> os.stat("D:\Deepti\SPSE-Course-DVD\Exercises\sample.xml" ) nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=219334L, st_atime=1441614421L, st_mtime=1441614386L, st_ctime=1441614421L) >>> os.lstat("D:\Deepti\SPSE-Course-DVD\Exercises\sample.xml") nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=219334L, st_atime=1441614421L, st_mtime=1441614386L, st_ctime=1441614421L)


No comments:

Post a Comment