文件操作是数据处理中的基础操作,包括读取、写入、存储/关闭等
#文件不存在时自动创建
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)
————来自韦玮老师课堂笔记