PY爬虫极速学习 (四)文件操作 异常处理

2019-11-06  本文已影响0人  罗卡恩

文件操作

image.png

先创建一个记事本 写一些东西


image.png

记得保存 UTF-8 不然之后会一直报错


image.png
#文件的操作
#打开
#open(文件地址,操作形式,编码格式)
'''
w 写入
r 读取
b 二进制
a 追加 
'''
fh=open("D://新建文本文档.txt","r",encoding="utf-8")
print(fh) #<_io.TextIOWrapper name='D://新建文本文档.txt' mode='r' encoding='cp936'>
data=fh.read() #全部读取
print(data) #你好啊
#一行一行读取
line=fh.readline()
print(line)
fh.close()#关闭文件

#读一行的方式读完
fh=open("D://新建文本文档.txt","r",encoding="utf-8")
x=0
while True :
    line2=fh.readline()
    if(len(line2)==0):#len()返回字符串长度
        break
    print(line2)
    x+=1
print(x)
fh.close()

#文件的写入 
#会把之前内容替换掉
data="一起学Py"
fh2=open("D://新建文本文档.txt","w",encoding="utf-8")
fh2.write(data)
fh2.close()
#追加写入 是在之后写入
fh2=open("D://新建文本文档.txt","a+",encoding="utf-8")
fh2.write("学好py")

异常处理

image.png
#异常处理
'''
异常处理格式
try:
    程序
except Exception as error:
    异常处理部分
'''

try:
    for i in range(0,10):
        print(i)
        if(i==4):
          print(jkj)#变量未定义
    print("hello")
except Exception as error:
    print(error)
image.png
#让异常后的程序继续
for i in range(0,10):
    try:
        print(i)
        if(i==4):
          print(jkj)#变量未定义
    except Exception as error:
        print(error)
print("hello")
image.png

所以try except 的位置很重要

上一篇 下一篇

猜你喜欢

热点阅读