10-1 Python学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
with open ('note.txt') as file_object:
print(file_object.read().rstrip())
10-2 C语言学习笔记 :可使用方法replace() 将字符串中的特定单词都替换为另一个单词。
with open ('note.txt') as file_object:
lines = file_object.readlines();
for line in lines:
print(line.replace('Python','C').rstrip())
10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
with open ('guest_book.txt','a') as file_object:
while True:
name = input("What's your name(input quit to quit):")
if name == 'quit':
break
file_object.write(name+'\n')
10-5 关于编程的调查 :编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
with open ('reason.txt','a') as file_object:
while True:
name = input("Why do you like promgramming(input quit to quit):")
if name == 'quit':
break
file_object.write(name+'\n')
10-7 加法计算器 :将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
while True:
print()
addend = input("What's the addend(Enter 'q' to quit):")
if addend == 'q':
break
try:
addend = int(addend)
except ValueError:
print("Sorry, the " + addend + " is not a digit.")
continue
augend = input("What's the augend(Enter 'q' to quit):")
if augend == 'q':
break
try:
augend = int(augend)
except ValueError:
print("Sorry, the " + augend + " is not a digit.")
continue
print("The result of " + str(addend) + " plus " + str(augend) + " is " + str(addend + augend) + ".")
10-8 猫和狗 :创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行
def animal_name(filename):
try:
with open(filename) as fileobject:
lines = fileobject.readlines()
except FileNotFoundError:
print("Sorry, the file " + filename + " does not exist.")
else:
print(filename + ":")
for line in lines:
print(line.rstrip())
animals = ["cat.txt","dog.txt"]
for animal in animals:
animal_name(animal)
print()
10-9 沉默的猫和狗 :修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发。
def animal_name(filename):
try:
with open(filename) as fileobject:
lines = fileobject.readlines()
except FileNotFoundError:
pass
else:
print(filename + ":")
for line in lines:
print(line.rstrip())
animals = ["cat.txt","dog.txt"]
for animal in animals:
animal_name(animal)
10-10 常见单词 :编写一个程序,它读取你在项目Gutenberg中获取的文件,并计算单词'the' 在每个文件中分别出现了多少次。
try:
with open("The American Journal of Archaeology.txt") as fileobject:
lines = fileobject.readlines()
except FileNotFoundError:
print("Sorry, the file The American Journal of Archaeology.txt does not found.")
else:
amount_the = 0
for line in lines:
amount_the += line.lower().count('the')
print("The word 'the' appears " + str(amount_the) + " times.")
10-12 记住喜欢的数字 :将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。
import json
favorite_number = input("What's you favorite number? ")
file_name = "favorite_number.json"
with open(file_name,'w') as file_object:
json.dump(favorite_number,file_object)
try:
with open(file_name) as file_object:
favorite_number = json.load(file_object)
print("I knowyour favorite number! It's " + favorite_number)
except FileNotFoundError:
favorite_number = input("What's you favorite number?")
with open(file_name,'w') as file_object:
json.dump(favorite_number,file_object)
print("I knowyour favorite number! It's " + favorite_number)