python第五周作业——chapter 10 文件和异常

Chapter 10

本次课主要讲了文件的读写和异常。第二次课讲了使用json存储数据

习题

10-1 Python学习笔记 : 在文本编辑器中新建一个文件, 写几句话来总结一下你至此学到的Python知识, 其中每一行都以“In Python you can”打头。 将这个文件命名为learning_python.txt, 并将其存储到为完成本章练习而编写的程序所在的目录中。 编写一个程序, 它读取这个文件, 并将你所写的内容打印三次: 第一次打印时读取整个文件; 第二次打印时遍历文件对象; 第三次打印时将各行存储在一个列表中, 再在with 代码块外打印它们。

知识点:从文件中读取数据

代码:

#10-1
path = 'learning_python.txt'

with open(path) as file_object:
    print(file_object.read())

print("\n")
with open(path) as file_object:

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

print("\n")
with open(path) as file_object:
    lines = file_object.readlines()

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

运行结果:

In Python you can store data in lists and dictionaries.
In Python you can build collections of data and work through them.
In Python you can use loops to test for certain conditions.
In Python you can accept input from users to make your programs interactive.
In Python you can write functions to make parts of your program reusable.
In Python you can create classes to make simple programs respond to various situations.

In Python you can store data in lists and dictionaries.
In Python you can build collections of data and work through them.
In Python you can use loops to test for certain conditions.
In Python you can accept input from users to make your programs interactive.
In Python you can write functions to make parts of your program reusable.
In Python you can create classes to make simple programs respond to various situations.

In Python you can store data in lists and dictionaries.
In Python you can build collections of data and work through them.
In Python you can use loops to test for certain conditions.
In Python you can accept input from users to make your programs interactive.
In Python you can write functions to make parts of your program reusable.
In Python you can create classes to make simple programs respond to various situations.


Q 10-4 访客名单 : 编写一个while 循环, 提示用户输入其名字。 用户输入其名字后, 在屏幕上打印一句问候语, 并将一条访问记录添加到文件guest_book.txt中。 确保这个文件中的每条记录都独占一行

知识点:写入文件,循环控制用户输入

代码:

filename = 'guest_book.txt'
with open(filename,'w') as file_object:
    while True:
        user = input("Please input your name:\nEnter 'q' to quit.\n")
        if user=='q':
            break
        print("Hi," + user.title()+'.\n')
        file_object.write(user.title()+'\n')
with open(filename) as file:
    print(file.read())

运行结果:

Please input your name:
Enter 'q' to quit.
Alice
Hi,Alice.

Please input your name:
Enter 'q' to quit.
bob
Hi,Bob.

Please input your name:
Enter 'q' to quit.
tom
Hi,Tom.

Please input your name:
Enter 'q' to quit.
q
Alice
Bob
Tom


Q 10-8 猫和狗:创建两个文件cats.txtdogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。 

知识点:异常

代码:

#10-8
files = ['cats.txt','dogs.txt']
for file in files:
    try:
        with open(file) as object:
            print(object.read()+'\n')

    except FileNotFoundError:
        print("Sorry,the file "+file+" does not exist.")

运行结果1:当txt文件均与代码文件位于同一目录下时

kitty
tom
bai

wangcai
fatty
erha

运行结果2:当将cats.txt移至其他位置时

Sorry,the file cats.txt does not exist.
wangcai
fatty
erha

Q 10-13 验证用户 : 最后一个remember_me.py版本假设用户要么已输入其用户名, 要么是首次运行该程序。 我们应修改这个程序, 以应对这样的情形: 当前和最后一次运行该程序的用户并非同一个人。

为此, 在greet_user() 中打印欢迎用户回来的消息前, 先询问他用户名是否是对的。 如果不对, 就调用get_new_username() 让用户输入正确的用户名。

知识点:json,重构

代码:

#10-13
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:
        verify = input("Are you " + username + "?(Yes/No)")
        if verify == 'Yes':
            print("Welcome back, " + username + '!')
        else:
            username = get_new_username()
            print("We'll remember you when you come back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")

greet_user()

首次运行结果:

What is your name? Eric
We'll remember you when you come back, Eric!

第二次运行结果:

Are you Eric?(Yes/No)No
What is your name? Haha
We'll remember you when you come back, Haha!

第三次运行结果:

Are you Haha?(Yes/No)Yes
Welcome back, Haha!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值