第十章-- 文件和异常

10.1 从文件中读取数据

10.1.1 读取整个文件

  • 创建pi_digits.txt
3.1415929535
  8979323846
  2643383279
  • file_reader.py
with open('pi_digits.txt') as file_object:
	contents = file_object.read()
	"""restrip()函数删除后面的空行"""
	print(contents.rstrip())
  • 结果为
    在这里插入图片描述

10.1.2 文件路径

相对路径打开
with open('text_files/filename.txt') as file_object:
with open('text_files\filename.txt') as file_object:

绝对路径打开
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:

file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:

10.1.3 逐行读取

with open('pi_digits.txt') as file_object:
	for line in file_object:
		print(line)

  • 结果为
    在这里插入图片描述

10.1.4 创建一个包含文件各行内容的列表

filename = 'pi_digits.txt'

with open(filename) as file_object:
"""
readlines()函数读取文件中的每一行,并存储在一个列表lines中,
在with 外部仍可以使用这个 lines 变量
"""
	lines = file_object.readlines()

for line in lines:
	print(line.rstrip())

10.1.5 使用文件的内容

  • python 在读取文件是,python 将其中的所有文本都解读为字符串。如果读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,或使用函数flost() 将其转换为浮点数
filename = 'pi_digits.txt'

with open(filename) as file_object:
	lines = file_object.readlines()

"""空字符串的目的是让该变量是字符数据类型"""
pi_string = ''
for line in lines:
	pi_string += line.rstrip() 删除后面的一行
	pi_string += line.strip()  删除后面的空格
print(pi_string)
print(len(pi_string))
  • 结果为
    在这里插入图片描述

10.1.6 包含一百万位的大型文件

10.1.7 圆周率值中包含你的生日吗

pi_string = ''
for line in lines:
	pi_string += line.rstrip() 删除后面的一行
	pi_string += line.strip()  删除后面的空格

birthday = input("Enter your birthday, in the form mmddyy: ")
"""使用if语句判断pi_string字符串中是否有birthday变量中的字符串,字符串不一定要相等,包含即可
"""
if birthday in pi_string:
	print("yes")
else:
	print("no")

10.2 写入文件

10.2.1 写入空文件

10.2.2 写入多行

filename = 'pi_digits.txt'
""" 'w' 会把文件之前的内容全部清除,再写"""
with open(filename,'w') as file_object:
	file_object.write('I love programming. \n')
	file_object.write('I love running. \n')
  • pi_digits.txt
    在这里插入图片描述

10.2.3 附加到文件

filename = 'pi_digits.txt'
""" 'a' 不会把文件之前的内容全部清除,只会在后面追加"""
with open(filename,'a') as file_object:
	file_object.write('I am crazy!. \n')
	file_object.write('I am master!. \n')
  • 结果为
    在这里插入图片描述

10.3 异常

10.3.1 处理 ZeroDivisionError 异常

10.3.2 使用 try-except 代码块

try:
	print(5/0)
except ZeroDivisionError:
	print("You can't divide by zero!")
  • 结果为
    在这里插入图片描述

10.3.3 使用异常避免崩溃

10.3.4 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("\nSecond number: ")
	try:
		answer = int(first_number) / int(second_number)
	except ZeroDivisionError:
		print("You can't divide by 0!")
	else: 
		print(answer)
  • 结果为
    在这里插入图片描述

10.3.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)
  • 结果为
    在这里插入图片描述

10.3.6 分析文本

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:
	# 计算文件大致包含多个单词
	"""split()函数根据一个字符串创建一个单词列表"""
	words = contents.split()
	num_words = len(words)
	print("The file "+ filename + " has about "+ str(num_words)+ "words.")
  • 结果为
    在这里插入图片描述
  • alice.txt 文件

在这里插入图片描述

10.3.7 使用多个文件


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:
		# 计算文件大致包含多个单词
		"""split()函数根据一个字符串创建一个单词列表"""
		words = contents.split()
		num_words = len(words)
		print("The file "+ filename + " has about "+ str(num_words)+ "words.")

filename = 'alice.txt'
count_words(filename)
filenames = ['alice.txt','pi_digits.txt']
for filename in filenames:
	count_words(filename)
  • 结果为
    在这里插入图片描述

10.3.8 失败时一声不吭

  • 在except FileNotFoundError:中使用 pass ,可令代码块使用它来让python什么都不要做
def count_words(filename):
	try:
		with open(filename) as f_obj:
			contents = f_obj.read()
	except FileNotFoundError:
		pass
	else:

10.3.8 决定报告哪些错误

10.4 存储数据

10.4.1 使用 json.dump() 和 json.load()

import json

numbers = [2, 3, 5, 7, 11, 13]
""".json文件不用预先创建,它会自动创建"""
"""通常使用.json数据格式来存储数据"""
filename = 'numbers.json'
"""往numbers.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(numbers)
  • 查看 numbers.json
    在这里插入图片描述
  • 打印 numbers.json
    在这里插入图片描述

10.4.2 保存和读取用户生成的数据

  • remember_me.py
import json
usernames = input("What is your name? ")

filename = 'username.json'
with open(filename,'w') as f_obj:
	"""把usernames 的值放入 f_obj 中"""
	json.dump(usernames, f_obj)
	print("We'll remember you when you come back ,"+ usernames +"!")
  • 结果为
    在这里插入图片描述
  • greet_user.py
import json
filename = 'username.json'

with open(filename) as f_obj:
	usernames = json.load(f_obj)
	print("Welcome back, " + usernames + "!")
  • 结果为
    在这里插入图片描述

10.4.3 重构

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()
  • 结果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值