《Python编程:从入门到实践》读书笔记:第10章 文件和异常

本章详细讲解了如何使用Python读取和写入文件,包括整文件读取、路径管理、逐行读取,以及处理ZeroDivisionError和FileNotFoundError等异常。通过实例演示了如何处理大型文件和搜索特定信息,同时介绍了如何优雅地存储和读取用户数据,以及使用json模块进行数据持久化。
摘要由CSDN通过智能技术生成

目录

第10章 文件和异常

10.1 从文件中读取数据

10.1.1 读取整个文件

10.1.2 文件路径

10.1.3 逐行读取

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

10.1.5 使用文件的内容

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

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

10.2 写入文件

10.2.1 写入空文件

10.2.2 写入多行

10.2.3 附加到文件

10.3 异常

10.3.1 处理ZeroDivisionError异常

10.3.2 使用try-except代码块

10.3.3 使用异常避免崩溃

10.3.4 else代码块

10.3.5 处理FileNotFoundError异常

10.3.6 分析文本

10.3.7 使用多个文件

10.3.8 静默失败

10.3.9 决定报告哪些错误

10.4 存储数据

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

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

10.4.3 重构


第10章 文件和异常

10.1 从文件中读取数据

10.1.1 读取整个文件

with open('pi_digits.txt') as file_object:
    contents = file_object.read()

print(contents)
3.1415926535 
  8979323846 
  2643383279

with open('pi_digits.txt') as file_object:
    contents = file_object.read()

print(contents.rstrip())
3.1415926535 
  8979323846 
  2643383279

10.1.2 文件路径

file_path = 'C:\\Users\\mm\\Desktop\\pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()

print(contents.rstrip())
3.1415926535 
  8979323846 
  2643383279

10.1.3 逐行读取

with open('pi_digits.txt') as file_object:
    for line in file_object:
        print(line)
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:
    for line in file_object:
        print(line.rstrip())
3.1415926535
  8979323846
  2643383279

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

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

10.1.5 使用文件的内容

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.141592653589793238462643383279
36
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.1.6 包含一百万位的大型文件

filename = 'pi_million_digits.txt'

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

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(f"{pi_string[:52]}...")
print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...
1000002

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

filename = 'pi_million_digits.txt'

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

pi_string = ''
for line in lines:
    pi_string += line.strip()

birthday = input("Enter your birthday, in the form mmddyy:")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi.")
Enter your birthday, in the form mmddyy:123456
Your birthday does not appear in the first million digits of pi.

10.2 写入文件

10.2.1 写入空文件

filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write('I love programming.')

Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。

10.2.2 写入多行

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')

10.2.3 附加到文件

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')
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使用称为异常的特殊对象来管理程序执行期间发生的错误。

10.3.1 处理ZeroDivisionError异常

print(5/0)
    print(5/0)
ZeroDivisionError: division by zero

10.3.2 使用try-except代码块

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
You can't divide by zero!

10.3.3 使用异常避免崩溃

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)
First number: 6
Second number: 0
    answer = int(first_number) / int(second_number)
ZeroDivisionError: division by zero

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("Second number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
Give me two numbers, and I'll divide them.
Enter 'q' to quit.

First number: 8
Second number: 0
You can't divide by 0!

10.3.5 处理FileNotFoundError异常

filename = 'alice.txt'

with open(filename, encoding='utf-8') as f:
    contents = f.read()
    with open(filename, encoding='utf-8') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist.")
Sorry, the file alice.txt does not exist.

10.3.6 分析文本

title = 'Alice in Wonderland'
print(title.split())
['Alice', 'in', 'Wonderland']
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exit.")
else:
    # 计算该文件大致包含多少个单词
    words = contents.split()
    num_words = len(words)
    print(f"The file {filename} has about {num_words} words.")
The file alice.txt has about 29465 words.

10.3.7 使用多个文件

def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exit.")
    else:
        # 计算该文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")


filename = 'alice.txt'
count_words(filename)
The file alice.txt has about 29465 words.
def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exit.")
    else:
        # 计算该文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {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 29465 words.
The file siddhartha.txt has about 42172 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.

10.3.8 静默失败

def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        pass
    else:
        # 计算该文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")


filenames = ['alice.txt', 'siddahartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
The file alice.txt has about 29465 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.

10.3.9 决定报告哪些错误

向用户显示他不想看到的信息可能会降低程序的可用性。Python的错误处理结构让你能够细致地控制与用户分享错误信息的程度,要分享多少信息由你决定。

10.4 存储数据

模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。

JSON格式最初是为JavaScript开发的,但随后成了一种常见的格式,被包括Python在内的众多语言采用。

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

import json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f:
    json.dump(numbers, f)
import json

filename = "numbers.json"
with open(filename) as f:
    numbers = json.load(f)

print(numbers)
[2, 3, 5, 7, 11, 13]

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

import json

username = input('What is your name? ')

filename = 'username.json'
with open(filename, 'w') as f:
    json.dump(username, f)
    print(f"We'll remember you when you come back, {username.title()}!")
What is your name? henry
We'll remember you when you come back, Henry!
import json

filename = 'username.json'

with open(filename) as f:
    username = json.load(f)
    print(f"Welcome back, {username.title()}!")
Welcome back, Henry!
import json
# 如果以前存储了用户名,就加载它。
# 否则,提示用户输入用户名并存储它。
filename = 'username.json'
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename, 'w') as f:
        json.dump(username, f)
        print(f"We'll remember you when you come back, {username.title()}!")
else:
    print(f"Welcome back, {username.title()}!")
Welcome back, Henry!

10.4.3 重构

import json


def greet_user():
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        username = input("What is your name? ")
        with open(filename, 'w') as f:
            json.dump(username, f)
            print(f"We'll remember you when you come back, {username.title()}!")
    else:
        print(f"Welcome back, {username.title()}!")


greet_user()

现在来重构greet_user(),减少其任务。

import json


def get_stored_username():
    """如果存储了用户名,就获取它。"""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username
    
    
def greet_user():
    """问候用户,并指出其名字。"""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username.title()}!")
    else:
        username = input("What is your name? ")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dump(username, f)
            print(f"We'll remember you when you come back, {username.title()}!")
            

greet_user()
import json


def get_stored_username():
    """如果存储了用户名,就获取它。"""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    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:
        json.dump(username, f)
    return username


def greet_user():
    """问候用户,并指出其名字。"""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username.title()}!")
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back, {username.title()}!")


greet_user()
What is your name? john
We'll remember you when you come back, John!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值