您的位置:首页 > 编程语言 > Python开发

Python基础知识——文件操作和异常处理

2018-03-12 20:52 686 查看
文件操作是数据处理中的基础操作,包括读取、写入、存储/关闭等#文件不存在时自动创建
a=open('D:/1python学习/重新学习python/file.txt','w')
b='hello,python'
a.write(b)
a.write('\nhi,girl')
a.close()
#文件存在时
a=open('D:/1python/file2.txt','r')
b=a.read()
print(b)
line1=a.readline() #读取第一行
print(line1)
while True:
line=a.readline()
if len(line)==0:
break
print(line)
a.close()操作过程中出现异常会终止程序运行,有个异常处理之后,我们可以读取异常并继续运行程序#异常处理
print('python')
prints('python')
try:
print('python')
prints('python')
except Exception as error: #捕捉异常并存储为error
print(error)————来自韦玮老师课堂笔记
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息