Search This Blog

Monday, September 28, 2015

Directory Navigation in Python - Command line

import os
import glob
import shutil
import fnmatch
import re


ex_path="D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob"
#Cleanup
print "Cleaning up"
if os.path.exists("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory"):
    os.rmdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

if os.path.exists(ex_path):
    # Remove directory and all its contents
    shutil.rmtree(ex_path)

print "Display the current directory path"
print "   %s" %os.getcwd()

print "Create a new directory"
os.mkdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

print "List contents of directory"
print os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2")

for item in os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2"):
    if os.path.isfile(item):
        print "  %s is a file" %item
    elif os.path.isdir(item):
        print "  %s is a directory" %item
    else:
        print "  %s: Unknown filetype" %item
     
print "Remove directory"
os.rmdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

print "List contents of directory"
print os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2")



# Pre-requisites

os.mkdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob")


file1=open(os.path.join(ex_path,"pythonfile.py"),"w")
file1.close()

file2=open(os.path.join(ex_path,"textfile.txt"),"w")
file2.close()

file3=open(os.path.join(ex_path,"swapfile.swp"),"w")
file3.close()

print "List contents of directory"
print os.listdir(ex_path)


# Exercise on glob
print "---- Print all the python files ----"
print glob.glob(os.path.join(ex_path,"*.py"))

# Exercise on fnmatch
print "---- Match file pattern using fnmatch ----"
print fnmatch.fnmatch(os.path.join(ex_path,"swapfile.swp"),"*.swp")
print fnmatch.fnmatchcase(os.path.join(ex_path,"SWAPFILE.swp"),"*.swp")
print fnmatch.fnmatchcase(os.path.join(ex_path,"waspfile.swp"),"*.swp")

# Prints False
print fnmatch.fnmatchcase(os.path.join(ex_path,"swapfile.SWP"),"*.swp")

fnmatch_pattern=fnmatch.translate("*.swp")
print fnmatch_pattern

reobj=re.compile(fnmatch_pattern)
print reobj

print reobj.match('swap.swp')

# Print set of files from a list of files
Files=['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py', 'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']
print 'Matches:', fnmatch.filter(Files,"*.py")







 

No comments:

Post a Comment