Python实现文件读写,并添加异常处理
Posted 杨艳春
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于Python实现文件读写,并添加异常处理的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式创建 MapView 并添加标记导致片段中出现空指针异常