通过Python新建一个文件gushi.txt,选择一首古诗写入文件中,再写一个另外的函数,读取指定文件gushi.txt,将内容复制到copy.txt中,并在控制台输出“复制完毕”,尽可能完善代码,添加异常处理。写的初级些
时间: 2023-04-08 15:01:38 浏览: 169
自己制作python编译器——pip.exe的复制修改——pip.py的开源压缩包
我可以回答这个问题。以下是Python代码:
# 写入古诗到gushi.txt文件中
def write_poem():
poem = "登高"
author = "杜甫"
content = "风急天高猿啸哀,\n渚清沙白鸟飞回。\n无边落木萧萧下,\n不尽长江滚滚来。"
with open("gushi.txt", "w", encoding="utf-8") as f:
f.write(f"{poem}\n{author}\n{content}")
# 读取gushi.txt文件并复制到copy.txt文件中
def copy_file():
try:
with open("gushi.txt", "r", encoding="utf-8") as f1, open("copy.txt", "w", encoding="utf-8") as f2:
f2.write(f1.read())
print("复制完毕")
except FileNotFoundError:
print("文件不存在")
except Exception as e:
print(f"发生错误:{e}")
# 调用函数
write_poem()
copy_file()
阅读全文