Search This Blog

Sunday, January 11, 2015

Python, Working with Directories and Files: Basics

C:\Work\MyWork\Python\Programs\Working_with_Dirs.py.html import os

#print the current working directory
print "CWD", os.getcwd()

#change the current working directory
os.chdir("C:\\temp")

print "CWD after changing ", os.getcwd()

#Given a directroy path, list all its contents.

""" listdir function is used for this purpose

the below line prints the list of contents in the
current working directory
"""

print os.listdir(os.getcwd())

#change CWD to some other directory and try
os.chdir("c:\\program files")

print os.listdir(os.getcwd())


#print only the file names
for f in os.listdir(os.getcwd()):
    if(os.path.isfile(f)):
        print "filename", f

#change to some other directory and try
os.chdir("C:\\program files\\7-zip")
for f in os.listdir(os.getcwd()):
    if(os.path.isfile(f)):
        print "filename", f


#print only directory names
os.chdir("c:\\program files")
for f in os.listdir(os.getcwd()):
    if(os.path.isdir(f)):
        print "Dir Name ", f


Back to Python Home Page

No comments:

Post a Comment