8、异常与import

#-*- 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)

try .. catch .. finally 嵌套

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("发生异常")

新建文件gushi.txt,写入一首古诗

def fwrite():
        fgushi=open("gushi.txt","w")
        fgushi.write("锄禾日当午,
"
                "汗滴禾下土。
"
                "谁知盘中餐,
"
                "粒粒皆辛苦。")
        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)

import 的概念

## 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+爬虫demodemo3urllib-test'
pathnew = r'E:技术学习Python+爬虫demodemo3	est'
os.rename(path,pathnew)

命令行导入模块

退出python命令行
exit()
pip install matplotlib

原文地址:https://www.cnblogs.com/moox/p/13199454.html