创建文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。 (1) 编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。 (2) 将程序代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并显示一条友好的消息。 (3) 将任意一个文件移到另一个地方,并确认except 代码块中的代码将正确执行。
时间: 2023-11-27 21:53:10 浏览: 60
(1) 读取文件内容并打印:
```python
try:
with open('cats.txt', 'r') as cats_file:
print("Cats:")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print("Dogs:")
print(dogs_file.read())
except FileNotFoundError:
print("One of the files could not be found.")
```
(2) 添加try-except代码块:
```python
try:
with open('cats.txt', 'r') as cats_file:
print("Cats:")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print("Dogs:")
print(dogs_file.read())
except FileNotFoundError:
print("One of the files could not be found.")
```
(3) 移动一个文件:
假设我们将`cats.txt`文件移动到另一个目录,我们可以通过修改文件路径来测试`except`代码块的执行:
```python
try:
with open('cats.txt', 'r') as cats_file:
print("Cats:")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print("Dogs:")
print(dogs_file.read())
except FileNotFoundError:
print("One of the files could not be found.")
```
阅读全文