题目参照《python编程——从入门到实践》第十章习题
10-1
with open('learning_python.txt') as file_object:
contents=file_object.read()
print(contents)
with open('learning_python.txt') as file_object:
for line in file_object:
print(line)
with open('learning_python.txt') as file_object:
lines=file_object.readlines()
for line in lines:
print(line)
10-3
name=input("Please write your name: ")
with open("guest.txt",'w') as file_object:
file_object.write(name+'\n')
10-6、10-7
while True:
try:
a=input("If you want to quit,please enter 'q',else write first number: ")
if a=='q':
break
b=input("If you want to quit,please enter 'q',else write second number: ")
if b=='q':
break
c=int(a)+int(b);
except ValueError:
print("Please write number!")
else:
print(c)
10-11、10-12
import json
try:
with open('number.json') as file_object:
number=json.load(file_object)
except FileNotFoundError:
number=input("What's your favorite number? ")
with open('number.json','w') as file_object:
json.dump(number,file_object)
else:
print("I know your favorite number!It's "+number)