作业:
- 应用文件操作的相关知识,通过Python新建一个文件gushi.txt,选择一首古诗写入文件中
- 另外写一个函数,读取指定文件gushi.txt,将内容复制到copy.txt中,并在控制台输出“复制完
毕”。 - 提示:分别定义两个函数,完成读文件和写文件的操作
尽可能完善代码,添加异常处理。
#-*- codeing = utf-8 -*-
#@Time :2022/5/3
#@Author :季白九月
#@File :demo1.py
#@Software: PyCharm
f = open('gushi.txt', 'w',encoding='utf-8')
f.write("垆边人似月,皓腕凝霜雪。")
f.close()
def du():
try:
f = open('gushi.txt', 'r',encoding='utf-8')
content = f.read()
return content
print("读取完毕")
except Exception as result:
print("捕获到了异常")
print(result)
finally:
f.close()
def xie(a):
try:
f = open('copy.txt', 'w', encoding='utf-8')
f.write(a)
print("复制完毕") # 如果write 操作有异常,此处的print就不会执行,直接跳转到 捕获
except Exception as result:
print("捕获到了异常")
print(result)
finally:
f.close()
try:
pp = du()
xie(pp)
except Exception as result:
print("捕获到了异常")
print(result)
finally:
print("读写过程已完成")
f = open('gushi.txt', 'r',encoding='utf-8')
不加 encoding=‘utf-8’ 中文会出现乱码
try:
f = open('copy.txt', 'w', encoding='utf-8')
f.write(a)
print("复制完毕") # 如果write 操作有异常,此处的print就不会执行,直接跳转到 捕获
except Exception as result:
print("捕获到了异常")
print(result)
finally:
f.close()
效果图如下: