首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python-文件操作/错误捕获/继承

2014-01-17 
python--文件操作/异常捕获/继承一、文件操作spathD:/test/baa.txt #设置spath值为路径fopen(spath,w

python--文件操作/异常捕获/继承

一、文件操作

spath="D:/test/baa.txt" #设置spath值为路径
f=open(spath,"w") #以写的权限打开文件夹,此时baa.txt不存在。
f.write("First line 1.\n")#写入First line 1 回车
f.writelines("First line 2.")+#向此前已打开的文本文件尾追加一行数据.

f.close()#关闭文件操作

f=open(spath,"r") # 以读权限打开文件

for line in f:
??? print line

f.close()

?

?

运行结果:

First line 1.

First line 2.

?

二、异常捕获

s=raw_input("Input your age:")
if s =="":
??? raise Exception("Input must no be empty.")

try:
??? i=int(s)
except ValueError:
??? print "Could not convert data to an integer."
except:
??? print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
??? print "You are %d" % i," years old"
finally: # Clean up action
??? print "Goodbye!"

?

运行结果:

Input your age:ad
Could not convert data to an integer.
Goodbye!

?

三、继承

?

class Base:
??? def __init__(self):
??????? self.data = []
??? def add(self, x):
??????? self.data.append(x)
??? def addtwice(self, x):
??????? self.add(x)
??????? self.add(x)

# Child extends Base
class Child(Base):
??? def plus(self,a,b):
??????? return a+b

oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2,3)

?

?

运行结果:

['str1']
5

?

热点排行