本文记录是自己这个小菜鸡Python学习笔记
《Python编程从入门到实践》第十章
#第十章 文件和异常
'''
自己创建文本文件pi_digits.txt,内容如下:
3.1415926535
8979323846
2643383279
'''
#10.1 从文件中读取数据
#读取整个文件
#Python在当前执行的文件所在的目录中查找指定的文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())
'''
3.1415926535
8979323846
2643383279
'''
#文件路径
#with open('text_files\filename.txt') as file_object:
#绝对路径:
#file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
#with open(file_path) as file_object:
with open('E:\Python\digits\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())
'''
3.1415926535
8979323846
2643383279
'''
#逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
'''
3.1415926535
8979323846
2643383279
'''
#创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
'''
3.1415926535
8979323846
2643383279
'''
#使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
'''
3.1415926535 8979323846 2643383279
36
'''
'''
读取文本文件时,Python将其中的所有文本都解读为字符串。
如果你读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,
或使用函数float()将其转换为浮点数。
'''
filename = 'pi_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))
'''
3.141592653589793238462643383279
32
'''
#10.2 写入文件
#写入空文件
#如果你要写入的文件不存在,函数open()将自动创建它
#open()函数第一个参数表示要带开的文件名称,第二个参数表示打开方式
#'r'读取模式
#'w'写入模式
#'a'附加模式
#'r+'读取和写入模式
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
'''
以写入('w')模式打开文件时千万要小心,
因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
'''
'''
这个程序没有终端输出,
但如果你打开文件programming.txt,将看到其中包含如下一行内容:
I love programming.
'''
#写入多行
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
'''
I love programming.I love creating new games.
'''
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
'''
I love programming.
I love creating new games.
'''
#附加到文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
'''
我们又写入了两行,它们被添加到文件programming.txt末尾:
I love programming.
I love creating new games.
I also love finding meaning in large datasets.
I love creating apps that can run in a browser.
'''
#10.3 异常
'''
每当发生让Python不知所措的错误时,它都会创建一个异常对象。
如果你编写了处理该异常的代码,程序将继续运行;
如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告
'''
#处理 ZeroDivisionError 异常
'''
你可能知道不能将一个数字除以0,但我们还是让Python这样做
print(5/0)
显然,Python无法这样做,因此你将看到一个traceback:
Traceback (most recent call last):
File "division.py", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
上述traceback中指出的错误ZeroDivisionError是一个异常对象
Python无法按你的要求做时,就会创建这种对象。
在这种情况下,Python将停止运行程序,并指出引发了哪种异常,
而我们可根据这些信息对程序进行修改。
'''
#使用 try-except 代码块
'''
当你认为可能发生了错误时,可编写一个try-except代码块来处理可能引发的异常。
你让Python尝试运行一些代码,并告诉它如果这些代码引发了指定的异常,该怎么办
处理ZeroDivisionError异常的try-except代码类似下面这样:
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
'''
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#使用异常避免崩溃
'''
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: ")
if second_number == 'q':
break
answer = int(first_number) / int(second_number)
print(answer)
这个程序没有采取任何处理错误的措施,
因此让它执行除数为0的除法运算时,它将崩溃
'''
#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 divided by 0! ")
else:
print(answer)
'''
try-except-else代码块的工作原理大致如下:
Python尝试执行try代码块中的代码;只有可能引发异常的代码才需要放在try语句中。
有时候,有一些仅在try代码块成功执行时才需要运行的代码;这些代码应放在else代码块中。
except代码块告诉Python,如果它尝试运行try代码块中的代码时引发了指定的异常,该怎么办
'''
'''
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: 5
Second number: 2
2.5
First number: q
'''
#处理 FileNotFoundError 异常
'''
使用文件时,一种常见的问题是找不到文件:
你要查找的文件可能在其他地方、文件名可能不正确或者这个文件根本就不存在。
对于所有这些情形,都可使用try-except代码块以直观的方式进行处理。
'''
'''
我们来尝试读取一个不存在的文件。
下面的程序尝试读取文件alice.txt的内容,但我没有将这个文件存储在alice.py所在的目录中
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
Python无法读取不存在的文件,因此它引发一个异常:
Traceback (most recent call last):
File "alice.py", line 3, in <module>
with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
'''
#分析文本
'''
方法split()以空格为分隔符将字符串分拆成多个部分,
并将这些部分都存储到一个列表中
'''
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)
else:
'''计算文件大概包含多少个单词'''
words = contents.split()
num_words = len(words)
print('The file ' +filename+ ' has about ' + str(num_words) + 'words.')
'''
The file alice.txt has about 17845words.
'''
#使用多个文件
def count_words(filename):
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.')
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
'''
The file alice.txt has about 17845words.
Sorry, the file siddhartha.txt does not exist.
Sorry, the file moby_dick.txt does not exist.
Sorry, the file little_women.txt does not exist.
'''
#失败时一声不吭
'''
在前一个示例中,我们告诉用户有一个文件找不到。
但并非每次捕获到异常时都需要告诉用户,有时候你希望程序在发生异常时一声不吭,就像什么都没有发生一样继续运行。
要让程序在失败时一声不吭,可像通常那样编写try代码块,但在except代码块中明确地告诉Python什么都不要做。
Python有一个pass语句,可在代码块中使用它来让Python什么都不要做
'''
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
'''计算文件大概包含多少个单词'''
words = contents.split()
num_words = len(words)
print('The file ' +filename+ ' has about ' + str(num_words) + 'words.')
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
'''
The file alice.txt has about 17845words.
'''
#10.4 存储数据
#这是一种在程序之间共享数据的简单方式
'''
一种简单的方式是使用模块json来存储数据。
'''
#使用json.dump()和json.load()
#使用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)
'''
我们先导入模块json,再创建一个数字列表
我们指定了要将该数字列表存储到其中的文件的名称filename = 'numbers.json'
通常使用文件扩展名.json来指出文件存储的数据为JSON格式
接下来,我们以写入模式打开这个文件,让json能够将数据写入其中
我们使用函数json.dump()将数字列表存储到文件numbers.json中
'''
#使用json.load()将这个列表读取到内存中
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
'''
[2, 3, 5, 7, 11, 13]
'''
#保存和读取用户生成的数据
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
'''
what is your name? Eric
We'll remember you when you come back, Eric!
'''
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, " + username + "!")
'''
Welcome back, Eric!
'''
#两者合并为一个程序
import json
'''
如果以前存储了用户名,就加载它
否则,就提示用户输入用户名并存储它
'''
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("we'll remember you when you come back, " +
username + "!")
else:
print("Welcome back, " + username + "!")
#重构
'''
代码能够正确地运行,但可做进一步的改进——将代码划分为一系列完成具体工作的函数。
这样的过程被称为重构。重构让代码更清晰、更易于理解、更容易扩展
'''
import json
def greet_user():
"""问候用户,并指出其名字"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
greet_user()
import json
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 greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
greet_user()
import json
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("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()