头歌平台Python实训答案——文件操作与异常处理
时间: 2023-11-22 17:05:17 浏览: 1129
第12章 python文件存取和异常处理-python基础,快速入门.pptx
头歌平台Python实训中的文件操作与异常处理的答案如下:
第1关:从文件中读取数据:
```python
n = int(input())
with open('src/Step1/test.txt') as file_object:
lines = file_object.readlines()
i = 0
for line in lines:
print(line.rstrip())
i += 1
if i == n:
break
```
第2关:将信息写入文件:
```python
s = input()
with open('src/Step2/test2.txt','w') as example:
example.write(s)
with open('src/Step2/test2.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
```
第3关:异常处理:
```python
import math
a = int(input())
try:
answer = math.sqrt(a)
except:
print("We can't take a root by minus")
else:
print(answer)
```
以上是头歌平台Python实训中对文件操作与异常处理的答案。
阅读全文