Jarrysoen 2022-06-26 01:49 采纳率: 66.7%
浏览 22
已结题

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()

  • 写回答

1条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-06-26 12:23
    关注

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

    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('复制完毕')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 7月4日
  • 已采纳回答 6月26日
  • 创建了问题 6月26日

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向