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

Python, Pickle Module




C:\Work\MyWork\Python\GTTS\Aromal\Pickle_1.py.html



import pickle

#create a list, We are going to pickle this list and store it in disk
mylist = ['Apple', 'Banana', 'Orange', 'Pineapple']

#open a temp file in write mode
fh = open("C:\\Temp\\test.txt", 'w')

# dump the list l into file
pickle.dump(mylist, fh)

#close the file
fh.close()

#now if we open and see our file, we can see that python has saved this list
#but with some extra characters

""" Now, load the file back into the python data structure"""

#opne the file for reading

fh = open("C:\\Temp\\test.txt", 'r')

#create and empty list
mylist2 = []

#load the data from file to mylist2
mylist2 = pickle.load(fh)

print mylist2

""" We'll see that the out put is

['Apple', 'Banana', 'Orange', 'Pineapple']

In this way pickle can be used to save and load python data structure
to and from disk

Some of the uses of the pickling

1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence)

2) sending python data over a TCP connection in a multi-core or distributed system (marshalling)

3) storing python objects in a database

4) converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).

"""


Back to Python Home Page