修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发。
def write_list(filename, tables):
with open(filename, 'a') as f1:
for table in tables:
f1.write(table+"\n")
cats = ['katte', 'bai', 'ming', 'hei']
dogs = ['xiao', 'lei', 'le']
write_list('cats.txt', cats)
write_list('dogs.txt', dogs)
def read_file(filename):
try:
with open(filename) as file_object:
content = file_object.read()
except FileNotFoundError:
pass
else:
print('The content of '+filename+" is:")
print(content.strip()+'\n')
names = ['cats.txt', 'dogs.txt', 'birds.txt']
for name in names:
read_file(name)

沉默的文件操作:处理不存在文件的异常
本文档展示了如何修改代码,使程序在尝试写入或读取文件时遇到缺失文件的情况保持静默,不抛出错误。重点在于处理 FileNotFoundError 的实例,以增强程序的健壮性。
470

被折叠的 条评论
为什么被折叠?



