Python-11.1-文件和异常-练习
练习一:读取文件
- 写出自己喜欢的水果,其中每一行都以"My favorite fruit is:"打头
- 编写一个程序将其读取出来
- 第一次打印时读取整个文件
- 第二次打印时读取时遍历文件对象
- 第三次打印时将各行存储在一个列表中,再在with代码快外打印它们
# 第一次打印
file_name = r'G:\qwh\favorite.txt'
with open(file_name) as file_object:
contents = file_object.read()
print(contents)
My favorite fruit is:apple
My favorite fruit is:pear
My favorite fruit is:banana
# 第二次打印
file_name = r'G:\qwh\favorite.txt'
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
My favorite fruit is:apple
My favorite fruit is:pear
My favorite fruit is:banana
# 第三次打印
file_name = r'G:\qwh\favorite.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
p = ""
for line in lines:
p += line
print(p)
My favorite fruit is:apple
My favorite fruit is:pear
My favorite fruit is:banana
练习二:使用方法replace()
- 将字符串中的特定单词都替换为另一个单词
- 将单词’favorite’替换成’best like’
# replace()
file_name = r'G:\qwh\favorite.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
p = ""
for line in lines:
line = line.replace('favorite', 'best like')
p += line
print(p)
My best like fruit is:apple
My best like fruit is:pear
My best like fruit is:banana
练习三:写入文件
- 编写一个程序,提示用户输入其名字或者登陆密码
- 用户做出相应后,将其名字写入到文件中
file_name = 'G:\qwh\login_name.txt'
a = ''
while True:
name = input("Input your login name:")
if name == 'quit':
break
else:
a = a + name + '\n'
continue
with open(file_name,'a') as file_object:
file_object.write(a + '\n')
Input your login name:kevin
Input your login name:job
Input your login name:jack
Input your login name:quit
file_name = 'G:\qwh\login_name_passwd.txt'
name_passwd = ''
login_name_passwd = ''
while True:
name = input("Input your login name:")
if name == 'quit':
break
else:
passwd = input("Input your login passwd:")
print()
name_passwd = name + " " + passwd
login_name_passwd = login_name_passwd + name_passwd + '\n'
continue
with open(file_name,'a') as file_object:
file_object.write(login_name_passwd + '\n')
Input your login name:jack
Input your login passwd:123456
Input your login name:kevin
Input your login passwd:98764
Input your login name:job
Input your login passwd:741258
Input your login name:quit
练习四:异常处理
- 编写一个程序,提示用户输入两个数字,再将它们相加并打印结果
- 在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误信息
- 利用while循环,让用户犯错(输入的是文本而不是数字)后能够继续输入数字
print("Give me two number, and I'll add them.")
print("Enter 'q' to quit.\n")
while True:
first_number = input("Enter first number:")
if first_number == 'q':
break
second_number = input("Enter second number:")
try:
first_number = int(first_number)
second_number = int(second_number)
except ValueError:
print("Please enter the correct number.\n")
else:
new_number = int(first_number) + int(second_number)
print(new_number)
print('\n')
Give me two number, and I’ll add them.
Enter ‘q’ to quit.
Enter first number:6
Enter second number:5555
5561
Enter first number:l
Enter second number:1
Please enter the correct number.
Enter first number:77
Enter second number:11
88
Enter first number:q
练习五:使用文件的内容
- 编写一个程序,尝试读取文件,并将其打印到屏幕上
- 将这些代码放在一个try-except代码块中,以便在文件不存在时捕获 FileNotFoundError 错误,并打印一条友好的消息
# version1.0
def read_file(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("Sorry, the file " + filename + " does not exist.\n")
else:
print(filename + " : ")
print("\t" + contents)
filenames = [r"G:\qwh\tuy.txt", r"G:\qwh\programming.txt"]
for filename in filenames:
read_file(filename)
Sorry, the file G:\qwh\tuy.txt does not exist.
G:\qwh\programming.txt :
jack
job
kevin
# version2.0
def read_file(filename):
try:
with open(filename) as file_object:
lines = file_object.readlines()
except FileNotFoundError:
print("Sorry, the file " + filename + " does not exist.\n")
else:
print(filename + " :")
for line in lines:
print("\t" + line.strip())
filenames = [r"G:\qwh\tuy.txt", r"G:\qwh\programming.txt"]
for filename in filenames:
read_file(filename)
Sorry, the file G:\qwh\tuy.txt does not exist.
G:\qwh\programming.txt :
jack
job
kevin
def read_file(filename):
"""阅读文件"""
try:
with open(filename) as file_object:
lines = file_object.readlines()
except FileNotFoundError:
print("Sorry, the file " + filename + " does not exist.\n")
else:
num = 0
for line in lines:
num = num + line.count('job')
print(num)
# filename = [r"G:\qwh\programming.txt"]
filename = r"G:\qwh\programming.txt"
read_file(filename)
1
练习六:使用方法cout()
- 编写一个程序,读取文件
- 并计算’fruit’在文件中出现了多少次
def read_file(filename):
"""读取文本文件"""
try:
with open(filename) as file_object:
lines = file_object.readlines()
except:
print("Sorry, the file " + filename + " does not exist.\n")
pass
else:
num = 0
for line in lines:
num = num + line.lower().count('fruit')
print(filename)
print(num)
print()
filenames = [r"G:\qwh\favorite.txt", r"G:\qwh\lop.txt", r"G:\qwh\fruit.txt"]
for filename in filenames:
read_file(filename.strip())
G:\qwh\favorite.txt
84
Sorry, the file G:\qwh\lop.txt does not exist.
G:\qwh\fruit.txt
6
def read_file(filename):
"""读取文本文件"""
try:
with open(filename) as file_object:
lines = file_object.readlines()
except:
pass
else:
num = 0
for line in lines:
num += line.lower().count('fruit')
print(filename)
print(num)
num = str(num)
add_file = "G:\\qwh\\addfile.txt"
with open(add_file, 'a') as addfile:
addfile.write(num + '\n')
filenames = [r"G:\qwh\favorite.txt", r"G:\qwh\lop.txt", r"G:\qwh\fruit.txt"]
for filename in filenames:
read_file(filename.strip())
add_file = "G:\\qwh\\addfile.txt"
with open(add_file) as add:
lines = add.readlines()
adds = 0
for line in lines:
adds += int(line)
print("\nThe numbers of documents:")
print(adds)
G:\qwh\favorite.txt
84
G:\qwh\fruit.txt
6
The numbers of documents:
90
练习七:存储数据
- 编写一个程序
- 如果存储了用户喜欢的数字,就使用json.load()从文件读取这个值,并打印消息"I know your favorite number is {}"
- 否则提示用户输入他喜欢的数字,并使用json.dump()将其存储到文件中
# version1.0
import json
filename = r"G:\qwh\favorite_number.json"
try:
with open(filename) as file_obj:
number = json.load(file_obj)
except FileNotFoundError:
number = input("What is your favorite number?")
with open(filename, 'w') as file_obj:
json.dump(number, file_obj)
print("The number you enter is {}.".format(str(number)))
else:
print("I know your favorite number is {}".format(str(number)))
I know your favorite number is 1006
# version2.0
import json
filename = r"G:\qwh\favorite_number.json"
def read_number():
"""如果储存了数字,就读取"""
try:
with open(filename) as file_obj:
number = json.load(file_obj)
except FileNotFoundError:
return None
else:
return number
def enter_number():
"""提示用户输入数字"""
number = input("What is you favorite number?")
with open(filename, 'w') as file_obj:
json.dump(number, file_obj)
return number
def greet_number():
# 如果存储了数字,则打印出来
# 否则提示用户输入数字
number = read_number()
if number:
print("I know your favorite number is {}".format(str(number)))
else:
number = enter_number()
print("The number you enter is {}".format(str(number)))
greet_number()
I know your favorite number is 6
# version3.0
import json
filename = r"G:\qwh\new_favorite_number.json"
try:
with open(filename) as file_obj:
numbers = file_obj.read()
except FileNotFoundError:
while True:
number = input("What is your favorite number?")
if number == 'q':
break
else:
with open(filename, 'a') as file_obj:
file_obj.write(number + '\n')
print('\n')
else:
a = ""
for number in numbers:
a += number
print(a.strip())
558
554
559
练习八:验证用户
- 对于 username.json 假设用户要么已输入其用户名,要么是首次运行该程序
- 当前和最后一次运行该程序的用户并非是同一个人
- 为此,在greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的
- 如果不对,就调用 get_new_username() 让用户输入正确的用户名
# version3.0
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = r"G:\qwh\username.json"
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_new_username():
"""提示用户输入名字"""
username = input("What is your name?")
filename = r"G:\qwh\username.json"
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
name = input("What is you name?")
# 询问是否为同一人
if username == name:
print("Welcome back, " + username.title() + ".")
else:
username = greet_new_username()
print("We'll remember you when you come back, " + username.title() + ".")
greet_user()
What is you name?jack
Welcome back, Jack.