Python入门-文件和异常

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

file_name = "learning_python.txt"

with open(file_name) as file_object:
    contents = file_object.read()
    print(contents)

print('\n')
with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip())

print('\n')
file_lines = []
with open(file_name) as file_object:
    for line in file_object:
        file_lines.append(line.rstrip())

for line in file_lines:
    print(line)



10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。

file_name = "guest.txt"

with open(file_name, 'a') as file_object:
    while(True):
        name = input("Input your name('q' to quit):")
        if name == 'q':
            break
        file_object.write(name + '\n')        

10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

print('I will add two number')

try:
    first = int(input('(input two number)first:'))
    second = int(input('(input two number)second:'))
except ValueError:
    print('Please input number.')
else:
    print('The sum is', first+second)



10-7 加法计算器 :将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

print("I will add two number('q' to quit)")

while(True):
    try:
        first = input('(input two number)first:')
        if first == 'q':
            break
        f = int(first)
        second = input('(input two number)second:')
        if second == 'q':
            break
        s = int(second)
    except ValueError:
        print('Please input number.')
    else:
        print('The sum is', f+s)


10-11 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It's _____.”。

扫描二维码关注公众号,回复: 3361796 查看本文章

dump.py:

import json

number = input('input your favorite number:')

file_name = 'number.json'
with open(file_name, 'w') as f_obj:
    json.dump(number, f_obj)


load.py:

import json

file_name = 'number.json'
with open(file_name) as f_obj:
    number = json.load(f_obj)

print(number)



10-12 记住喜欢的数字 :将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

import json

file_name = 'number.json'

try:
    with open(file_name) as f_obj:
        remember_number = json.load(f_obj)
except FileNotFoundError:
    number = input('input your favorite number:')
    with open(file_name, 'w') as f_obj:
        json.dump(number, f_obj)
else:
    print('Your favorite number is', remember_number)


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_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:
        current_name = input('Input your name:')
        if current_name == username:
            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()



猜你喜欢

转载自blog.csdn.net/james_154_best/article/details/79829020
今日推荐