分类: Python/Ruby
2012-12-27 10:39:16
十七、python中向本地写入文件
将新的内容写入到D:\soft\poem.txt中去
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('D:\soft\poem.txt', 'w') # 这里使用的是写模式,还有读模式‘r’,追加模式('a')
f.write(poem) # write text to file
f.close() # 最后记得关闭输入流
十八、python中的追加模式
import cPickle as p #注意引入的东西
shoplistfile = 'D:\soft\shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
f = file(shoplistfile, 'a') #使用追加模式的话,就是重复的添加数据。但是读取出来的数据还是
p.dump(shoplist, f)
f.close()
del shoplist
f = file(shoplistfile)
storedlist = p.load(f) #注意使用的是load
print storedlist
这样读取出来的文件是:
['apple', 'mango', 'carrot']
---------------------------------------------------------------------
如果是使用这样:
f = file(shoplistfile)
while True:
line = f.readline()
if len(line)==0:
break
print line,
那么读取出来的文件时这样的:
(lp1
S'apple'
p2
aS'mango'
p3
aS'carrot'
p4
a.
十九、python中的继承
class SchoolMember: #父类
def __init__(self, name, age): #表示子类的参数,2个,self相当于this
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
print 'Name:"%s" Age:"%s"' % (self.name, self.age)
class Teacher(SchoolMember): #子类
def __init__(self, name, age, salary): #---------注意这里还要使用 SchoolMember.__init__(self, name, age)
SchoolMember.__init__(self, name, age) #---------这个时候开始子类的参数就变成了--3--个
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
二十、python中异常处理
class myException(Exception): #这里表示的是继承了Exception父类
def __init__(self,length,atleastlen):
Exception.__init__(self) #原来的父类中是没有参数的
self.length=length
self.atleastlen=atleastlen
try:
s = raw_input('input your string:')
if(len(s))<5:
raise myException(len(s),5) #注意使用的是raise来实现异常的捕获
except EOFError: #这个是通常要写的
print 'why did you do an EOF on me'
except myException,my: #--------这里的my相当于一个对象
print 'the length of you inputed :%s is shorter than :%d'%(my.length,my.atleastlen) #--打印异常信息
else:
print 'That is right,No Exception'