标签:ret url pychar cti war file return pen dem
#-*- codeing = utf-8 -*-
#@Time : 2020/6/7 20:28
#@Author : zhangfudong
#@FILE :Errors and Expections.py
#@Software : PyCharm
有错误发生时,会直接中断程序,因此需要捕获异常并处理
print ("-----test1-----")
f = open ("123.txt", "r") ## 只读方式打开不存在的123.txt时,会报错直接退出程序
print ("-----test2-----") ## 上一句程序报错,此处不会被执行
try:
print ("-----test1-----")
f = open ("123.txt", "r")
print ("-----test2-----")
except IOError: ## FileNotFoundError属于IOError
pass ## 捕获异常后执行的代码
try:
print ("-----test1-----")
f = open ("test.txt", "r")
print ("-----test2-----")
print(num)
except IOError: ##异常类型需要一致,否则无法被捕获
## 将所有的异常类型都放小括号中,实际异常可以使用as保存
## except (NameError,IOError) as exp_log:
except Exception as exp_log: ## Exception表示所有异常
print("发生错误了")
print(exp_log)
import time
try:
f=open("test.txt","r")
try:
while True:
content=f.readline()
if len(content)==0:
break
time.sleep(2)
print(content)
finally:
f.close()
print("文件关闭")
except Exception as result:
print("发生异常")
def fwrite():
fgushi=open("gushi.txt","w")
fgushi.write("锄禾日当午,\n"
"汗滴禾下土。\n"
"谁知盘中餐,\n"
"粒粒皆辛苦。")
fgushi.close()
def fread():
try:
fgushi = open("gushi.txt", "r")
fcopy = open ("copy.txt", "w")
while True:
content=fgushi.readline()
if len(content)==0:
break
fcopy.write(content)
print("复制完毕")
except Exception as copy_log:
print(copy_log)
finally:
fgushi.close()
try:
fwrite()
fread()
except Exception as result:
print ("发生异常")
print (result)
## dir1中新建文件test1.py
def add(a,b):
sum=a+b
return(sum)
## dir2中的文件test2.py调用test1.py中的函数
from dir1 import test1
print(test1.add(13,15))
import os
os.remove("gushi.txt")
os.remove("copy.txt")
import os
path = r‘E:\技术学习\Python+爬虫\demo\demo3\urllib-test‘
pathnew = r‘E:\技术学习\Python+爬虫\demo\demo3\test‘
os.rename(path,pathnew)
退出python命令行
exit()
pip install matplotlib
标签:ret url pychar cti war file return pen dem
原文地址:https://www.cnblogs.com/moox/p/13199454.html