try.except,finally语句的使用方法

问题遇到的现象和发生背景

python网课的作业题,我只写出了下面代码实现了题目要求的运算结果,但是不会使用def函数,不知道应该在哪里使用try,except,finally语句添加异常处理,求指点。

img

我写出的代码

f = open("gushi.txt","w")
f.write("白日依山尽,黄河入海流。""\n""欲穷千里目,更上一层楼。""\n")
f.close()
f = open("gushi.txt")
copy = open("copy.txt","w")
content = f.readlines()
for i in content:
copy.write(i)
f.close()
copy.close()

常见的错误就是文件找不到,或编码错误,可以指定错误类型进行输出:

def writefile(filepath, content, encoding='utf-8'):
    try:
        f = open(filepath,'w',encoding=encoding)
        f.write(content)
        f.close()
    except UnicodeEncodeError:
        print("编码错误")
    except Exception as e:
        print("出现异常")
        print(e)

def readfile(filepath, encoding='utf-8'):
    try:
        f = open(filepath,'r',encoding=encoding)
        content = f.readlines()
        f.close()
        return ''.join(content)
    except FileNotFoundError:
        print("文件未找到")
    except UnicodeDecodeError:
        print("解码错误")
    except Exception as e:
        print("出现异常")
        print(e)


gushi = "白日依山尽,黄河入海流。\n欲穷千里目,更上一层楼。\n"
writefile("gushi.txt", gushi)

content = readfile('gushi.txt')
if content:
    writefile("copy.txt", content)
    print('复制完毕')