常见的错误就是文件找不到,或编码错误,可以指定错误类型进行输出:
def writefile(filepath, content, encoding='utf-8'):
try:
f = open(filepath,'w',encoding=encoding)
f.write(content)
f.close()
except UnicodeEncodeError:
print("编码错误")
except Exception as e:
print("出现异常")
print(e)
def readfile(filepath, encoding='utf-8'):
try:
f = open(filepath,'r',encoding=encoding)
content = f.readlines()
f.close()
return ''.join(content)
except FileNotFoundError:
print("文件未找到")
except UnicodeDecodeError:
print("解码错误")
except Exception as e:
print("出现异常")
print(e)
gushi = "白日依山尽,黄河入海流。\n欲穷千里目,更上一层楼。\n"
writefile("gushi.txt", gushi)
content = readfile('gushi.txt')
if content:
writefile("copy.txt", content)
print('复制完毕')