第十章 文件和异常
动手试一试代码实现
(1)习题内容
10-1 Python学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以 “In Python you can” 大头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with代码块外打印它们。
10-2 C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的‘dog’替换为‘cat’:
message = "I really like dogs."
message.replace('dog','cat')
输出结果为 ‘ I really like cat. ’
读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
10-4 访客名单:编写一个while循环,提示用户输入名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这个文件中的每条记录都独占一行。
10-5 关于编程的调查:编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因额文件中。
10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误信息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
10-7 加法计算器:将你为完成练习 10-6 而编写的代码放在一个while循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
10-8 猫和狗:创建两个文件cat.txt和dog.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印存在时到屏幕上。将这些代码放在 try_except 代码块中,以便在文件不存在时捕获 FileNotFound错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except代码块中的代码将正确地执行。
10-9 沉默的猫和狗:修改你在练习 10-8 中编写的except代码块,让程序在文件不存在时一言不发。
10-10 常见单词:访问项目 Gutenberg(http://gutenberg.org/),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
你可以使用方法count()来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算‘row’在一个字符串中出现了多少次:
line = “Row,row,row your boat”
line.count(‘row’)
2
line.lower().count(‘row’)
3
请注意,通过使用lower()将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。
编写一个程序,它读取你在项目 Gutenberg 中获取的文件,并计算单词 ‘the’ 在每个文件中分别出现了多少次。
10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s _____.”。
10-12 记住喜欢的数字:将练习 10-11 中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。
10-13 验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。
为此,在greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username()让用户输入正确的用户名。
(2)代码实现
# coding=utf-8
# 10-1 Python学习笔记
# 第一次打印时读取整个文件
with open('learning_python.txt') as file_object:
file_contents=file_object.read()
print(file_contents.rstrip())
print("\n")
# 第二次打印时遍历文件对象
file_name='learning_python.txt'
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
print("\n")
# 第三次打印时将各行存储在一个列表中再在with代码块外打印它们
file_name='learning_python.txt'
with open(file_name) as file_object:
file_lines=file_object.readlines()
for line in file_lines:
print(line.rstrip())
print("\n")
# 10-2 C语言学习笔记
file_name='learning_python.txt'
with open(file_name) as file_object:
file_lines=file_object.readlines()
new_content=''
for line in file_lines:
new_content=line.replace('Python','C')
print(new_content.rstrip())
print("\n")
# 10-3 访客
file_name1='guest.txt'
user_name=input("Please input your name:")
with open(file_name1,'w') as file_object:
file_object.write(user_name)
print("\n")
# 10-4 访客名单
file_name2='guest_book.txt'
name2="\nPlease input your name:"
name2 += "\n(You can input 'quit' if you want to quit.)"
while True:
user_name2=input(name2)
if user_name2 == 'quit':
break
else:
with open(file_name2,'a') as file_object:
file_object.write(user_name2.title()+"\n")
print("Hello,"+user_name2.title()+".")
# 10-5 关于编程的调查
file_name3='programming_survey.txt'
answer="\nPlease tell me the reason why you leve programming:"
answer += "\n(You can input 'quit' if you want to quit.)"
while True:
love_reason=input(answer)
if love_reason == 'quit':
break
else:
with open(file_name3,'a') as file_object:
file_object.write(love_reason+"\n")
print("\n")
# 10-6 加法运算
try:
num_input_1=input("Please input the first number:")
num_input_1=int(num_input_1)
num_input_2=input("Please input the second number:")
num_input_2=int(num_input_2)
num_add=num_input_1 + num_input_2
except ValueError:
print("Your input is not valid,please input number.")
else:
print("The sum of "+str(num_input_1)+" and "+str(num_input_2)+" is "+str(num_add)+".")
print("\n")
# 10-7 加法计算器:
print("Please input 'quit' when you want to quit.")
while True:
try:
num_input_1=input("Please input the first number:")
if num_input_1 =='quit':
break
num_input_1=int(num_input_1)
num_input_2=input("Please input the second number:")
if num_input_2 =='quit':
break
num_input_2=int(num_input_2)
num_add=num_input_1 + num_input_2
except ValueError:
print("Your input is not valid,please input number.")
else:
print("The sum of "+str(num_input_1)+" and "+str(num_input_2)+" is "+str(num_add)+".")
print("\n")
# 10-8 猫和狗
def print_content_file(file_names):
try:
with open(file_names) as file_object:
contents=file_object.readlines()
except FileNotFoundError:
print("Sorry,the file "+file_names+" does not exit.")
else:
for content in contents:
print(content.strip())
file_names=['cats.txt','dogs.txt']
for file_na in file_names:
print("\nContents of file '"+file_na+"':")
print_content_file(file_na)
print("\n")
# 10-9 沉默的猫和狗
def print_content_file(file_names):
try:
with open(file_names) as file_object:
contents=file_object.readlines()
except FileNotFoundError:
pass
else:
for content in contents:
print(content.strip())
file_names=['cats.txt','dogs.txt']
for file_na in file_names:
print("\nContents of file '"+file_na+"':")
print_content_file(file_na)
print("\n")
# 10-10 常见单词
def count_words(f_names):
try:
with open(f_names) as file_object:
contents=file_object.read()
except FileNotFoundError:
print("Sorry,the file "+file_names+" does not exit.")
else:
word_the_numbers=contents.lower().count('the')
print("The word 'the' appears "+str(word_the_numbers)+" times in the file '"+f_names+"'.")
f_names='alice.txt'
count_words(f_names)
print("\n")
# 10-11 喜欢的数字
# 第一个程序:
import json
favor_number=input("Please input your favorite number:")
file_name4='favor_number.json'
with open(file_name4,'w') as file_object:
json.dump(favor_number,file_object)
# 第二个程序:
import json
file_name4='favor_number.json'
with open(file_name4) as f_object:
fav_number=json.load(f_object)
print("\nI know your favorite number!It's "+str(fav_number)+".")
print("\n")
# 10-12 记住喜欢的数字
import json
file_name5='favorite_num.json'
try:
with open(file_name5) as f_ob:
favor_num=json.load(f_ob)
except FileNotFoundError:
favor_num=input("Please input your favorite number:")
with open(file_name5,'w') as f_obj:
json.dump(favor_num,f_obj)
else:
print("I know your favorite number!It's "+str(favor_num)+".")
print("\n")
# 10-13 验证用户
import json
# 如果存储了用户名,就获取它user
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
# 提示用户输入正确的用户名
def get_new_username():
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
# 问候用户,并指出其名字
def greet_user():
username = get_stored_username()
if username:
print("User's name is "+username+" at present.")
ask_correct = input("Is your name correct?yes/no:")
if ask_correct == 'yes':
print("Welcome back,"+username+"!")
else:
print("Please input your correct name!")
username = get_new_username()
print("We'll remember you when you come back, "+username+"!")
else:
username = get_new_username()
print("We'll remember you when you come back, "+username+"!")
greet_user()