第十章 文件和异常
10-1 Python学习笔记
with open("hw.txt") as file_object:
contents = file_object.read()
print (contents)
with open("hw.txt") as file_object:
for line in file_object.readlines():
print (line)
with open("hw.txt") as file_object:
li = file_object.readlines()
print (li)
10-2 C语言学习笔记
with open("hw.txt") as file_object:
contents = file_object.readlines()
for line in contents:
line = line.replace("Python", "C")
print (line.rstrip())
10-3 访客
name = input("Please input your name: ")
with open("guest.txt", "w") as file_object:
file_object.write(name)
10-4 访客名单
with open("guest_book.txt", "w") as file_object:
while True:
name = input("Please input your name: ")
greeting = "Welcome, " + name
print (greeting)
file_object.write(greeting + "\n")
10-5 关于编程的调查
with open("Reason.txt", "w") as file_object:
while True:
reason = input("Why do you love programing? ")
file_object.write(reason + "\n")
10-6 加法运算
print ("Please input two numbers: ")
try:
number1 = input()
number1 = int(number1)
number2 = input()
number2 = int(number2)
except ValueError:
print ("Your input is informal")
else:
print ("The numbers' addition you input is " + str(int(number1) + int(number2)))
10-7 加法计算器
while True:
print ("Please input two numbers: ")
try:
number1 = input()
number1 = int(number1)
number2 = input()
number2 = int(number2)
except ValueError:
print ("Your input is informal")
else:
print ("The numbers' addition you input is " + str(int(number1) + int(number2)))
10-8 猫和狗
try:
with open("cats.txt") as file_object:
print (file_object.read())
except FileNotFoundError:
print ("The file you want is not exist.")
10-9 沉默的猫和狗
try:
with open("cats.txt") as file_object:
print (file_object.read())
except FileNotFoundError:
pass
10-11 喜欢的数字
import json
filename = "hw.json"
with open(filename, "w") as file_object:
number = input("Please input your faviourite number: ")
json.dump(number, file_object)
with open(filename) as file_object:
number = json.load(file_object)
print ("I know it " + number)
10-12 记住喜欢的数字
import json
filename = "hw.json"
try:
with open(filename) as file_object:
number = json.load(file_object)
print (number)
except FileNotFoundError:
with open(filename, "w") as file_object:
number = input("Please input your faviourite number: ")
number = int(number)
json.dump(number, file_object)