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)

浙公网安备 33010602011771号