• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
杨艳春
博客园    首页    新随笔    联系   管理    订阅  订阅

Python实现文件读写,并添加异常处理

 

 没使用函数

#写古诗到文件中
f = open("gushi.txt","w",encoding="utf-8") #不加encoding="utf-8"文件会出现乱码
f.write('''
静夜思
李白
窗前明月光,疑是地上霜。
举头望明月,低头思故乡。
''')
f.close()

#复制:先读出文件中内容,再写入新的文件
f = open("gushi.txt","r",encoding="utf-8")
m = open("copy.txt","w",encoding="utf-8")

content = f.readlines()
# m.write(content) 不能这样写,write()里面只能写字符串,不能写列表
for i in content:
m.write(i)

f.close()
m.close()

 

使用函数

 def writeFile(filename,content):
f = open(filename,"w",encoding="utf-8")
for i in content:
f.write(i)
f.close()

def readFile(filename):
f = open(filename,"r",encoding="utf-8")
contents = f.readlines()
return contents
f.close()

gushi = ["日照香炉生紫烟\n","遥看瀑布挂前川\n","飞流直下三千尺\n","疑似银河落九天\n"]
writeFile("gushi.txt",gushi)
contents = readFile("gushi.txt")
copy = []
for content in contents:
copy.append(content)
writeFile("copy.txt",copy)

 加上异常捕获

try:

def writeFile(filename,content):
f = open(filename,"w",encoding="utf-8")
for i in content:
f.write(i)
f.close()

def readFile(filename):
f = open(filename,"r",encoding="utf-8")
contents = f.readlines()
return contents
f.close()

gushi = ["日照香炉生紫烟\n","遥看瀑布挂前川\n","飞流直下三千尺\n","疑似银河落九天\n"]
writeFile("gushi.txt",gushi)
contents = readFile("gushi.txt")
copy = []
for content in contents:
copy.append(content)
writeFile("copy.txt",copy)
print("复制完毕")

except Exception as result:
print("产生错误了")
print(result)

 

posted @ 2020-11-13 14:22  猫耳朵白  阅读(374)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3