《Python编程从入门到实践》_第十章_文件和异常
print("10 文件和异常")
print("10.1.1读取整个文件")
with open('pi_digits.txt') as file_object:
contens = file_object.read()
print(contens)
print(contens.rstrip())# rstrip()删除字符串末尾的空白
print("绝对路径")
file_path = 'H:\pi_digits.txt'
with open(file_path) as file_object:
contens1 = file_object.read()
print(contens1)
print("10.1.3 逐行读取")
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
# 为何出现这些空白行 因为在这个文件中 每行的末尾都有一个看不见的换行符,而print语句也会加上一个换行符
print("消除这些多余的空白行 可在print语句中使用rstrip()")
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("10.1.4创建一个包含文件各行内容的列表")
# 方法readlines()从文件中读取每一行,并将其存储在一个列表中;
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
# 在with代码块外 我们依然可以使用这个变量
for line in lines:
print(line.rstrip())
print("10.1.5使用文件的内容")
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))
print("pi_string存储的字符串中 包含原来位于每行左边的空格 为删除这些空格 可使用strip()而不是rstrip()")
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))
# 读取文本文件时候 python将其中的所有文本都解读为字符串 如果你读取的是数字 并要将其作为数值使用 就必须使用函数int()将其转化为整数
print("10.1.6包含一百万位的大型文件")
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[:10]+"...")
print(len(pi_string))
print("10.1.7圆周率值包含你的生日")
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input("Enter you birthday,int the form mmddy! ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi! ")
else:
print("no")
###############################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
10 文件和异常
10.1.1读取整个文件
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279
绝对路径
3.1415926535
8979323846
2643383279
10.1.3 逐行读取
3.1415926535
8979323846
2643383279
消除这些多余的空白行 可在print语句中使用rstrip()
3.1415926535
8979323846
2643383279
10.1.4创建一个包含文件各行内容的列表
['3.1415926535\n', ' 8979323846\n', ' 2643383279']
3.1415926535
8979323846
2643383279
10.1.5使用文件的内容
3.1415926535 8979323846 2643383279
36
pi_string存储的字符串中 包含原来位于每行左边的空格 为删除这些空格 可使用strip()而不是rstrip()
3.141592653589793238462643383279
32
10.1.6包含一百万位的大型文件
3.14159265...
32
10.1.7圆周率值包含你的生日
Enter you birthday,int the form mmddy! 141592
Your birthday appears in the first million digits of pi!
Process finished with exit code 0
####################################################################################
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love kankan\n")
with open(filename) as file_object:
contens = file_object.read()
print(contens.strip())
# 在这个示例中,调用open()时提供了两个实参(见Ø)。
# 第一个实参也是要打开的文件的名称;
# 第二个实参('w')告诉Python,我们要以写入模式打开这个文件。
# 打开文件时,可指定读取模式('r')、 写入模式('w')、
# 附加模式('a')或让你能够读取和写入文件的模式('r+')。如果你省略了模式实参,
# Python将以默认的只读模式打开文件。
print("附加到文件")
print("10.2.2 写入多行")
# 要让每个字符串都单独占一行 需要在write()语句中包含换行符
with open(filename, 'a') as file_object:
file_object.write("I also love python\n")
file_object.write("aaa\n")
with open(filename) as file_object:
contens = file_object.read()
print(contens.strip())
#####################################################################################3
C:\Anaconda3\python.exe H:/python/venv/pizza.py
I love kankan
I love kankan
I also love python
aaa
Process finished with exit code 0
#######################################################################################
print("10.3处理异常")
print("10.3.1处理ZeroDivisionError异常")
# print(5/0) ZeroDivisionError: division by zero
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero! ")
print("10.3.3使用异常避免崩溃")
print("Give me two numebers, 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
try:
answer = int(first_number) / int(second_number) # ZeroDivisionError: division by zero
except ZeroDivisionError:
print("You can't divide by zero! ")
# 依赖于try代码块成功执行代码需要放到else代码块中
else:
print(answer)
#####################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
10.3处理异常
10.3.1处理ZeroDivisionError异常
You can't divide by zero!
10.3.3使用异常避免崩溃
Give me two numebers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by zero!
First number: 5
Second number: 2
2.5
First number: 5
Second number: 1
5.0
First number:
###################################################################################
print("10.3.5继续处理FileNotError")
# FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
file_name = 'pi_digits.txt'
try:
with open(file_name) as f_obj:
conten = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + file_name + " does not exist. "
print(msg)
print("10.3.6分析文本")
title = 'Alice in Wonderland'
print(title.split())
try:
with open(file_name) as f_obj:
conten = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + file_name + " does not exist. "
print(msg)
else:
# 计算文件大致包含多少个单词
words = conten.split()
num_words =len(words)
print("The file " + file_name + " has abput " + str(num_words) + " words.")
print("10.3.7 使用多个文件")
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contens = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist. "
print(msg)
else:
# 计算文件大致包含多少个单词
words = contens.split()
num_words = len(words)
print("The file " + file_name + " has abput " + str(num_words) + " words.")
filename = 'pi_digits.txt'
count_words(filename)
filenames = ['programming.txt', 'pi_digits.txt', 'aaaaa.txt']
for filename in filenames:
count_words(filename)
print("10.3.8 失败时一声不吭")
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contens = f_obj.read()
except FileNotFoundError:
pass
else:
# 计算文件大致包含多少个单词
words = contens.split()
num_words = len(words)
print("The file " + file_name + " has abput " + str(num_words) + " words.")
filenames = ['programming.txt', 'pi_digits.txt', 'aaaaa.txt']
for filename in filenames:
count_words(filename)
######################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
10.3.5继续处理FileNotError
10.3.6分析文本
['Alice', 'in', 'Wonderland']
The file pi_digits.txt has abput 3 words.
10.3.7 使用多个文件
The file pi_digits.txt has abput 3 words.
The file pi_digits.txt has abput 8 words.
The file pi_digits.txt has abput 3 words.
Sorry, the file aaaaa.txt does not exist.
10.3.8 失败时一声不吭
The file pi_digits.txt has abput 8 words.
The file pi_digits.txt has abput 3 words.
Process finished with exit code 0
######################################################################################
JSON模块
很多程序都要求用户输入某种信息,如让用户存储游戏首选项或提供要可视化的数据。不管专注的是什么,程序都把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,你几乎总是要保存他们提供的信息;一种简单的方式是使用模块json来存储数据。
模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json在Python程序之间分享数据。更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。这是一种轻便格式,很有用,也易于学习。
import json
info={'name': 'Tom',
'age': '12',
'job': 'work', }
f=open('file1.txt', 'w')
f.write(json.dumps(info))
f.close()
print("number_writer.py")
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
#####################################################################################
import json
filename = 'number.json'
with open(filename) as f_obj:
# json.load()将这个列表读取到内存中
numbers = json.load(f_obj)
print(numbers)
print("10.4.2保存和读取用户的数据")
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 + " ! ")
#####################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
[2, 3, 5, 7, 11, 13]
10.4.2保存和读取用户的数据
what is your name? Mars
we'll remember you when you come back, Mars !
Process finished with exit code 0
####################################################################################
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print(" Welcome back, " + username + " ! ")
##################################################################################
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 + " ! ")
#################################如果这个程序首次运行####################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
What is your name? Tom
We'll remember you when you come back, Tom !
Process finished with exit code 0
#################################如果执行过一次#########################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
Welcome back., Tom !
Process finished with exit code 0
######################################################################################
import json
print("10.4.3重构")
# 否则 就提示用户输入用户名存储他
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()
####################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
10.4.3重构
Welcome back., Tom !
Process finished with exit code 0
###################################################################################
import json
print("10.4.3重构1")
# 否则 就提示用户输入用户名存储他
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? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + " ! ")
greet_user()
##################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
10.4.3重构1
Welcome back., Tom !
Process finished with exit code 0
#################################################################################
import json
print("10.4.3重构2")
# 只负责获取并存储的用户名
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()
########################################################################################
C:\Anaconda3\python.exe "D:\soft\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 60350 --file H:/python/venv/pizza.py
pydev debugger: process 3808 is connecting
Connected to pydev debugger (build 181.5087.37)
10.4.3重构2
What is your name? Mars
We'll remember you when you come back, Mars !
Process finished with exit code 0
#########################################################################################