您的位置:首页 > 编程语言 > Python开发

Python第五周第二次作业

2018-04-08 00:12 274 查看
学习文件的处理  
10-1 学习笔记
创建一个名为note的txt文档with open('note.txt') as fil:
context = fil.read()
print(context)
print()

with open('note.txt') as fil:
for line in fil:
print(line.strip())
print()

with open('note.txt') as fil:
lines = fil.readlines()
for line in lines:
print(line.strip())



readlines()为一个包含每行内容的列表,而readline()为一个包含一行中每个字符的列表,重复使用就能逐行遍历
10-6 加法运算
有了异常处理,就可以解决文本转数字失败的情况了while True:
print("Enter 'q' to quit!")
first_num = input("Please input the first number:")
if(first_num == 'q'):
break
try:
first_num = int(first_num)
except ValueError:
print("The number is wrong!")
else:
second_num = input("Please input the second number:")
if(second_num == 'q'):
break
try:
second_num = int(second_num)
except ValueError:
print("The number is wrong!")
else:
print(first_num + second_num)



10-12 记住喜欢的数字
json似乎不能当作文档一样储存多次内容?因此我只好将之前储存过的内容提出来,将新加的内容接到后面……import json

def show_num():
print("Your favorite numbers:", end = '')
try:
with open('number.json') as fil:
numbers = json.load(fil)
print(numbers)
except FileNotFoundError:
print("None")

def get_num():
try:
with open('number.json') as fil:
numbers = json.load(fil)
except FileNotFoundError:
numbers = ''
numbers += input("Please input your favorite number:")
numbers += ' '
with open('number.json', 'w') as fil:
json.dump(numbers, fil)

def favo_num():
show_num()
get_num()
show_num()
print("")

favo_num()



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: