Python编程:从入门到实践(第二版)随书敲代码 第十章 文件和异常

file_reader.py

filename = 'pi_digits.txt'

with open(filename) as file_object:

    lines = file_object.readlines()

for line in lines:

    print(line.rstrip())

pi_string.py

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

birthday = input("Enter your birthday, in the form mmddyy: ")

if birthday in pi_string:

    print("Your birthday appers in the first million digits of pi!")

else:

    print("Your birthday does not appear in the first million digits of pi.")

learning_python.py

# 练习 10-1 Python 学习笔记

# 在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中

# 每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储

# 到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你

# 所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次

# 打印时将各行存储在一个列表中,再在 with 代码块外打印它们。

filename = 'learning_python.txt'

print("--- Reading in the entire file:")

with open(filename) as file_object:

    contents = file_object.read()

print(contents)

print("\n--- Looping over the lines:")

with open(filename) as file_object:

    for line in file_object:

        print(line.rstrip())

print("\n--- Storing the lines in a list:")

with open(filename) as file_object:

    lines = file_object.readlines()

for line in lines:

    print(line.rstrip())

learning_python_to_c.py

# 练习 10-2 C 语言学习笔记

# 你可使用方法 replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简

# 单的示例,演示了如何将句子中的 'dog' 替换为 'cat' :

# >>> message = "I really like dogs."

# >>> message.replace('dog', 'cat')

# 'I really like cats.'

# 读取你刚创建的文件 learning_python.txt 中的每一行,将其中的 Python 都替换为另一

# 门语言的名称,如 C。将修改后的各行都打印到屏幕上。

filename = 'learning_python.txt'

with open(filename) as f:

    lines = f.readlines()

for line in lines:

    # 删除行尾的换行符,再将 Python 替换为 C。

    line = line.rstrip()

    print(line.replace('Python', 'C'))

# 可在一行代码中依次调用 rstrip() 和 replace() ,这被称为方法串接。在下面的代

# 码中,删除行尾的换行符再将 Python 替换为 C,输出与前面的代码相同。

filename = 'learning_python.txt'

with open(filename) as f:

    lines = f.readlines()

for line in lines:

    # 删除行尾的换行符,再将 Python 替换为 C。

    print(line.rstrip().replace('Python', 'C'))

write_message.py

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

write_message_a.py

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

guest_input.py

# 练习 10-3 访客

# 编写一个程序,提示用户输入其名字;用户做出响应后,将其名字写入到文件 guest.txt中。

name = input("What's your name? ")

filename = 'guest.txt'

with open(filename, 'w') as f:

    f.write(name)

guest_input_record.py

# 练习 10-4 访客名单

# 编写一个 while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印问候

# 语,并将一条到访记录添加到文件 guest_book.txt 中。确保这个文件中的每条记录都独占一行。

filename = 'guest_book.txt'

print("Enter 'quit' when you are finished.")

while True:

    name = input("\nWhat's your name? ")

    if name == 'quit':

        break

    else:

        with open(filename, 'a') as f:

            f.write(f"{name}\n")

        print(f"Hi {name}, you've been added to the guest book.")

guest_poll.py

# 练习 10-5 调查

# 编写一个 while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。

filename = 'programming_poll.txt'

responses = []

while True:

    response = input("\nWhy do you like programming? ")

    responses.append(response)

    continue_poll = input("Would you like to let some one else respond?(y/n) ")

    if continue_poll != 'y':

        break

with open(filename, 'a') as f:

    for response in responses:

        f.write(f"{response}\n")

division_calculator.py

try:

    print(5/0)

except ZeroDivisionError:

    print("You can't divide by zero!")

division_calculator1.py

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 devide by 0!")

    else:

        print(answer)

alice.py

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.")

else:

    # 计算该文件大致包含多少个单词.

    words = contents.split()

    num_words = len(words)

    print(f"The file {filename} has about {num_words} words.")

word_count.py

def count_words(filename):

    """计算一个文件大致包含多少个单词."""

    try:

        with open(filename, encoding='utf-8') as f:

            contents = f.read()

    except FileNotFoundError:

        pass

        # print(f"Sorry, the file {filename} does not exist.")

    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)

addition_operation.py

# 练习 10-6 加法运算

# 提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数。在这

# 种情况下,当你尝试将输入转换为整数时,将引发 ValueError 异常。编写一个程序,提

# 示用户输入两个数,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕

# 获 ValueError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两

# 个数,再输入一些文本而不是数。

try:

    x = input("Give me a number: ")

    x = int(x)

    y = input("Give me another number: ")

    y = int(y)

except ValueError:

    print("Sorry, I really needed a number.")

else:

    sum = x + y

    print(f"The sum of {x} and {y} is {sum}.")

addition_calculator.py

# 练习 10-7 加法计算器

# 将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让用户犯错(输入的是

# 文本而不是数)后能够继续输入数。

print("Enter 'q' at any time to quit.")

while True:

    try:

        x = input("\nGive me a number: ")

        if x == 'q':

            break

        x = int(x)

        y = input("Give me another number: ")

        if y == 'q':

            break

        y = int(y)

    except ValueError:

        print("Sorry, I really needed a number.")

    

    else:

        sum = x + y

        print(f"The sum of {x} and {y} is {sum}.")

cats_and_dogs.py

# 练习 10-8 猫和狗

# 创建两个文件 cats.txt 和 dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个

# 文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏

# 幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound

# 错误,并打印一条友好的消息。将文件之一移到另一个地方,并确认 except 代码块中的

# 代码将正确地执行。

filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:

    print(f"\nReading file: {filename}")

    try:

        with open(filename) as f:

            contents = f.read()

            print(contents)

    except FileNotFoundError:

        print("Sorry, I can't find that file.")

silent_cats_and_dogs.py

filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:

    print(f"\nReading file: {filename}")

    try:

        with open(filename) as f:

            contents = f.read()

            print(contents)

    except FileNotFoundError:

        pass

    

    else:

        print(f"\nReading file: {filename}")

        print(contents)

common_words.py

# 练习 10-10 常见单词

# 访问古登堡计划(http://gutenberg.org/),并找一些你想分析的图书。下载这些作品的

# 文本文件或将浏览器中的原始文本复制到文本文件中。

# 你可使用方法 count() 来确定特定的单词或短语在字符串中出现了多少次。例如,下

# 面的代码计算 'row' 在一个字符串中出现了多少次:

# >>> line = "Row, row, row your boat"

# >>> line.count('row')

# 2

# >>> line.lower().count('row')

# 3

# 请注意,通过使用 lower() 将字符串转换为小写,可捕捉要查找的单词的各种外观,

# 而不管其大小写格式如何。

# 编写一个程序,它读取你在古登堡计划中获取的文件,并计算单词'the'在每个文件

# 中分别出现了多少次。这里计算得到的结果并不准确,因为将诸如'then'和'there'等

# 单词也计算在内了。请尝试计算'the '(包含空格)出现的次数,看看结果相差多少。

def count_common_words(filename, word):

    """计算指定的单词在图书中出现的次数."""

    try:

        with open(filename, encoding='utf-8') as f:

            contents = f.read()

    except FileNotFoundError:

        pass

    else:

        word_count = contents.lower().count(word)

        msg = f"'{word}' appears in {filename} about {word_count} times."

        print(msg)

filename = 'alice.txt'

count_common_words(filename, 'the')

number_write.py

import json

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

filename = 'numbers.json'

with open(filename, 'w') as f:

    json.dump(numbers, f)

number_write_load.py

import json

filename = 'numbers.json'

with open(filename) as f:

    numbers = json.load(f)

     

print(numbers)

remember_me.py

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}!")

greet_user.py

import json

filename = 'username.json'

with open(filename) as f:

    username = json.load(f)

    print(f"Welcome back, {username}!")

remember_me1.py

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(f)

        print(f"We'll remember you when you come back, {username}!")

else:

    print(f"Welcome back, {username}!")

remember_me2.py

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}!")

    else:

        print(f"Welcome back, {username}!")

greet_user()

remember_me3.py

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}!")

    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}!")

greet_user()

remember_me4.py

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}!")

    else:

        username = get_new_username()

        print(f"We'll remember you when you come back, {username}!")

greet_user()

---------------------------------------------------------------------------------------------------------------------------------

favorite_number.write.py

# 练习 10-11 喜欢的数

# 编写一个程序,提示用户输入他喜欢的数,并使用 json.dump() 将这个数字存储到文

# 件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s 

# _____.”。

import json

filename = 'favorite_number.json'

number = input("What's your favorite number? ")

with open(filename, 'w') as f:

    json.dump(number, f)

    print("Thanks! I'll remember that.")

favorite_number_read.py

import json

filename = 'favorite_number.json'

with open(filename) as f:

    number = json.load(f)

print(f"I know your favorite number! It's {number}.")

---------------------------------------------------------------------------------------------------------------------------------

remember_favorite_number.py

# 练习 10-12 记住喜欢的数

# 将练习 10-11 中的两个程序合而为一。如果存储了用户喜欢的数,就向用户显示它;

# 否则提示用户输入他喜欢的数并将其存储到文件中。运行这个程序两次,看看它是否像预

# 期的那样工作。

import json

filename = 'favorite_number.json'

try:

    with open(filename) as f:

        number = json.load(f)

except FileNotFoundError:

    number = input("What's your favorite number? ")

    with open(filename, 'w') as f:

        json.dump(number, f)

    print("Thanks, I'll remember that.")

else:

    print(f"I know your favorite number! It's {number}.")

---------------------------------------------------------------------------------------------------------------------------------

check_user.py

# 练习 10-13 验证用户

# 最后一个 remember_me.py 版本假设用户要么已输入其用户名,要么是首次运行该程

# 序。应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个

# 人。

# 为此,在 greet_user() 中打印欢迎用户回来的消息前,询问他用户名是否是对的。如

# 果不对,就调用 get_new_username() 让用户输入正确的用户名。

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:

        correct = input(f"Are you {username}? (y/n) ")

        if correct =='y':

            print(f"Welcome back, {username}!")

            return

    

    username = get_new_username()

    print(f"We'll remember you when you come back, {username}!")

greet_user()

---------------------------------------------------------------------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值