Python Day 9 2020-4-25
Python 文件和异常
从文件中读取数据
1.读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
(1)函数open,打开文件
函数open()接受一个参数:要打开的文件的名称。Python在当前执行的文件所在的目录中查找指定的文件。
(2)关键字with在不再需要访问文件后将其关闭。
也可以调用open()和close()来打开和关闭文件,但这样做时,如果程序存在bug,导致close()语句未执行,文件将不会关闭。
(3)方法read()读取这个文件的全部内容,并将其作为一个长长的字符串存储在变量中。
相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。可在print语句中使用rstrip()消除空行。
2.文件路径
(1)相对文件路径
相对文件路径让Python到指定的位置去查找,而该位置是相对于当前运行的程序所在目录的。
with open('text_files\filename.txt') as file_object:
(2)绝对文件路径
文件在计算机中的准确位置。
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
3.逐行读取
要以每次一行的方式检查文件,可对文件对象使用for循环:
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
4.创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表。
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
方法readlines()从文件中读取每一行,并将其存储在一个列表中。
5.使用文件的内容
将文件读取到内存中后,就可以以任何方式使用这些数据了。
filename = 'pi_30_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
6.包含一百万位的大型文件:列表切片方式显示部分
7.检查字符是否在列表中:列表存储后使用if语句来进行判断。
写入文件
1.写入空文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
(1)读取模式(‘r’)
(2)写入模式(‘w’)
(3)附加模式(‘a’)
(4)能够读取和写入文件的模式(‘r+’)
(5)如果省略了模式实参,Python将以默认的只读模式打开文件。
(6)如果要写入的文件不存在,函数open()将自动创建它。然而,以写入(‘w’)模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
(7)文件对象的方法write()将一个字符串写入文件。
2.写入多行
注意添加换行符,空格,制表符等。
3.附加到文件
(1)如果要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。以附加模式打开文件时,Python不会在返回文件对象前清空文件,而写入到文件的行都将添加到文件末尾。如果指定的文件不存在,Python将创建一个空文件。
(2)指定了实参’a’,以便将内容附加到文件末尾,而不是覆盖文件原来的内容。
异常
1.处理 ZeroDivisionError 异常
2.使用 try-except 代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
如果try代码块中的代码运行起来没有问题,Python将跳过except代码块;如果try代码块中的代码导致了错误,Python将查找这样的except代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。
3.使用异常避免崩溃
4.else 代码块
将可能引发错误的代码放在try-except代码块中,可提高这个程序抵御错误的能力。
于try代码块成功执行的代码都应放到else代码块中。
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
5.处理 FileNotFoundError 异常
是找不到文件
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
6.分析文本
方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
7.使用多个文件
可以将try—except代码移到不同的函数中。
8.失败时一声不吭
Python有一个pass语句,可在代码块中使用它来让Python什么都不要做。
except FileNotFoundError:
pass
8.决定报告哪些错误
如用户输入、存在指定的文件、有网络链接,就有可能出现异常。
存储数据
模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json在Python程序之间分享数据。
1.使用 json.dump()和 json.load()
(1)函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
(2)用json.load()将这个列表读取到内存中。
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
2.保存和读取用户生成的数据
将json.dump()和 json.load()用try—except连接起来。
3.重构
将代码划分为一系列完成具体工作的函数。这样的过程被称为重构。重构让代码更清晰、更易于理解、更容易扩展。
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
--snip--
def get_new_username():
"""提示用户输入用户名"""
--snip--
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()
课后练习
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 cats.’
读取你刚创建的文件 learning_python.txt 中的每一行,将其中的 Python 都替换为另一门语言的名称,如 C。将修改后的各行都打印到屏幕上。
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件 guest.txt 中。
10-4 访客名单:编写一个 while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这个文件中的每条记录都独占一行。
10-5 关于编程的调查:编写一个 while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发 TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获 TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
10-7 加法计算器:将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
10-8 猫和狗:创建两个文件 cats.txt 和 dogs.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()让用户输入正确的用户名。
# -*- coding: GBK -*-
import json
#10-1-2
with open('learning_python.txt') as file_object:
files=file_object.read()
print(files)
for fliess in file_object:
print(fliess)
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string=line.strip()
print(pi_string)
print(line.replace('Python','C').strip()+'\n')
#10-3
with open('guest.txt','w') as users:
users.write(input('Please enter a user name:'))
#10-4
with open('guest_book.txt','a') as users:
action=True
while action:
users.write(input('Please enter a user name:')+'\n')
print('Welcome your coming!')
if input('The end of the input(yes/no):')=='yes':
action=False
else:
action=True
#10-6
try:
unmber=int(input("Please enter the first number:"))
unmber1=int(input("Please enter the second number:"))
except ValueError:
print('Please enter a number!')
else:
sum=unmber+unmber1
print('The sum of these two Numbers is:'+str(sum))
#10-7
while True:
try:
unmber=int(input("Please enter the first number:"))
unmber1=int(input("Please enter the second number:"))
except ValueError:
print('Please enter a number!')
else:
sum=unmber+unmber1
print('The sum of these two Numbers is:'+str(sum))
break
#10-8-9
try:
with open('cats.txt') as c_obj:
cats=c_obj.read()
print('The contents of the file are:'+cats)
except FileNotFoundError:
#print("Sorry, the file does not exist." )
pass
try:
with open('dogs.txt') as d_obj:
dogs=d_obj.read()
print('The contents of the file are:'+dogs)
except FileNotFoundError:
#print("Sorry, the file does not exist." )
pass
#10-10
filename='nana.txt'
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
msg="Sorry,the file"+filename+"does not exist."
print(msg)
else:
words=contents.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
print("The number of 'the' word in this file is:"+
str(contents.lower().count('the')))
#10-11
numbers=input('Please enter your favorite number:')
filename='favorite_number.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
with open(filename) as f_obj:
numbers=json.load(f_obj)
print("I know your favorite number! It's "+numbers+".")
#10-12
filename='favorite_number.json'
try:
with open(filename) as f_obj:
numbers=json.load(f_obj)
except FileNotFoundError:
numbers=input('Please enter your favorite number:')
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
print("I know your favorite number! It's "+numbers+".")
else:
print("I know your favorite number! It's "+numbers+".")
#10-13
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?\n")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
user="Your username is "+username+ "?"
print(user)
my_user=input("Please enter (yes / no):")
if my_user=='yes':
print("Welcome back,"+username+"!")
else:
username = get_new_username()
print("We'll remember you when you come back,"+username+"!")
greet_user()