题目:
10-8 猫和狗:创建两个文件cats.txt 和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。
10-9 沉默的猫和狗:修改你在练习10-8 中编写的except 代码块,让程序在文件不存在时一言不发。
catsfilepath='cats.txt'
dogsfilepath='dogs.txt'
try:
with open(catsfilepath) as fileobject:
lines=fileobject.readlines()
except FileNotFoundError:
print('未找到cats.txt文件!')
else:
for line in lines:
print(line.rstrip())
try:
with open(dogsfilepath) as fileobject:
lines=fileobject.readlines()
except FileNotFoundError:
print('未找到dogs.txt文件!')
else:
print('\n'.rstrip())
for line in lines:
print(line.rstrip())
#10-9的
try:
with open(dogsfilepath) as fileobject:
lines=fileobject.readlines()
except FileNotFoundError:
pass
else:
print('\n'.rstrip())
for line in lines:
print(line.rstrip())