python scripts the fifth day

第五天了。
先祝咱们周末愉快!
说起来python,学习有段时间了。一定要坚持下去。
做事不能一蹴而就,先来个温故而知新吧。
1,readit.py
print "Opening and closing the file."
text_file=open("read_it.txt", "r")
# before you can read from a text file, you need to open it
# i don't include any path information
# python looks in the current directory for the file
text_file.close()
# whenever you've done with a file, close it
print "\nReading characters from the file."
text_file=open("read_it.txt", "r")
print text_file.read(1)
print text_file.read(5)
print text_file.read()
text_file.close()
print "\nReading one line at a time."
text_file=open("read_it.txt", "r")
print text_file.readline()
print text_file.readline()
print text_file.readline()
text_file.close()
print "\nReading the entire file into a list."
text_file=open("read_it.txt","r")
lines=text_file.readlines()
print lines
print len(lines)
for line in lines:
        print line
text_file.close()
print "\nLooping through the file, line by line."
text_file=open("read_it.txt", "r")
for line in text_file:
        print line
text_file.close()
raw_input("\nPress the enter key to exit.")
# "r"        read from a file.
# "w"        write to a file
# "a"        append a file
# "r+"        read from and write to a file
# "w+"        write to and read from a file
# "a+"         append and read from a file
2,writeit.py
print "creating a text file with the write() method."
text_file=open("write_it.txt", "w")
text_file.write("line 1\n")
text_file.write("this is line 2\n")
text_file.write("that makes this line 3\n")
# write() method doesn't automatically insert a newline character
# at the end of a string it writes
# you have to put newlines in where you want them
text_file.close()
print "\nReading the newly created file."
text_file=open("write_it.txt", "r")
print text_file.read()
text_file.close()
print "\nCreating a text file with the writelines() method."
text_file=open("write_it2.txt", "w")
lines = ["line 1\n",
                "this is line 2\n",
                "that makes this line 3\n"]
text_file.writelines(lines)
text_file.close()
print "\nReading the newly created file"
text_file=open("write_it2.txt", "r")
print text_file.read()
text_file.close()
raw_input("\nPress the enter key to exit")
3,pickleit.py
import cPickle, shelve
print "Pickling lists."
variety=["sweet", "hot", "dill"]
shape=["whole", "spear", "chip"]
brand=["claussen", "heinz", "vlassic"]
pickle_file=open("pickles1.dat", "w")
cPickle.dump(variety, pickle_file)
cPickle.dump(shape, pickle_file)
cPickle.dump(brand, pickle_file)
pickle_file.close()
print "\nUnpickling lists."
pickle_file=open("pickles1.dat", "r")
variety=cPickle.load(pickle_file)
shape=cPickle.load(pickle_file)
brand=cPickle.load(pickle_file)
print variety, "\n", shape, "\n" , brand
pickle_file.close()
print "\nShelving lists."
pickles=shelve.open("pickles2.dat")
# shelve.open() function works with a file that stores pickled objects and not characters.
pickles["variety"]=["sweet", "hot", "dill"]
pickles["shape"]=["whole", "spear", "chip"]
pickles["brand"]=["claussen", "heinz", "vlassic"]
pickles.sync()        # make sure data is written
print "\nRetrieving the lists from a shelved file:"
for key in pickles.keys():
        print key, "-", pickles[key]
raw_input("\nPress the enter key to exit.")
4,handleit.py
try:
        num=float(raw_input("Enter a number:"))
except:
        print "something went wrong!"
# IOError
# IndexError
# KeyError
# NameError
# SyntaxError
# TypeError
# ValueError
# ZeroDivisionError
# specifying exception type
try:
        num=float(raw_input("\nEnter a number:"))
except (ValueError):
        print "That was not a number!"
# if you're not sure what the exception type is
# just create the exception
# handle multiple exceptions
print
for value in (None, "Hi!"):
        try:
                print "Attempting to convert", value, "-->",
                print float(value)
        except (TypeError, ValueError):
                print "Something went wrong!"
        except (TypeError):
                print "I can only convert a string or a number!"
        except (ValueError):
                print "i can only convert a string of digits!"
       
# get an exception's argument
try:
        num=float(raw_input("\nEnter a number:"))
except (ValueError) , e:
        print "That was not a number. or as python would say: \n", e
# try/except/else
try:
        num=float(raw_input("\nEnter a number:"))
except (ValueError):
        print "That was not a number"
else:
        print "You entered the number", num
raw_input("\nPress the enter key to exit.")
5,simple_critter.py
class Critter(object):
        """ A virtual pet"""
        def talk(self):
                print "Hi, I'm an  instance of class Critter."
                # you can think of methods as functions associated with an object
                # every method must have a special first parameter, called self by convention
                # it provides a way for a method to refer to the object itself
# main
crit=Critter()
crit.talk()
raw_input("\nPress the enter key to exit.")
6,constructor.py
class Critter(object):
        """ A virtual pet. """
        def __init__(self):
                print "A new critter has been born!"
        # constructor method (initialization method)
        # python has a collection of built-in "special methods"
        # whose names begin and end with two underscores, the constructor method
               
        def talk(self):
                print "\nHi i'm an instance of class critter"
       
# main
crit1=Critter()
crit2=Critter()
crit1.talk()
crit2.talk()
raw_input("\nPress the enter key to exit.")
7,attribute.py
class Critter(object):
        " " " A virtual pet " " "
        def __init__(self, name):
                print " A new critter has been born."
                self.name=name
               
        def __str__(self):
                rep="critter object\n"
                rep+="name:"+ self.name + "\n"
                return rep
        def talk(self):
                print " Hi, I'm ", self.name, "\n"
       
# main
crit1=Critter("Poochie")
crit1.talk()
crit2=Critter("Randolph")
crit2.talk()
print "Printing crit1:"
print crit1
print "Directly accessing crit1.name:"
print crit1.name
raw_input("\nPress the enter key to exit.")
download:

       
        文件:23.tar.gz
        大小:2KB
        下载:
下载