Python从入门到实践,总结笔记4:文件+异常+存储数据+测试

1,文件

文件打开:

with open('test_files/pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

逐行读取:

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

创建包含文件隔行内容的列表逐行读取:

with open('test_files/pi_digits.txt') as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    print(line.rstrip())
    pi_string += line.rstrip()
print(pi_string[:24])  # 只打印前24位
print(len(pi_string))

你的名字在圆周率里吗?

birthday = '92653'
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.")

写入文件:

with open('test_files/programming.txt', 'w') as file_object:
    file_object.write("I Love Programming.\n")
    file_object.write("I love creating new games.\n")

with open('test_files/programming.txt', '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")

 

2,异常

ZeroDivisionError:

try:  # ZeroDivisionError 异常处理
    answer = 5 / 0
except ZeroDivisionError:
    print("You can't divide by zero")
else:  # else 代码块
    print(str(answer))

 

使用异常避免程序崩溃:

def count_words(filename):  # 定义函数
    try:  # FileNotFoundError 异常处理
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file" + filename + "does not exist."
        print(msg)
        # pass  # 失败时一声不吭
    else:
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

3,存储数据

函数json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。

import json  # 存储数据

numbers = input("What is your numbers? ")
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)

使用函数json.load() 加载存储在numbers.json中的信息,并将其存储到变量numbers 中。

import json  # 存储数据

with open(filename) as f_obj:
    numbers = json.load(f_obj)
    print("We'll remember your numders, " + numbers + "!")

4,测试

单元测试 用于核实函数的某个方面没有问题;

测试用例 是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。

良好的测试用例考虑到了函数可能收到的各种输入,包含针对所有这些情形的测试。

全全覆覆盖盖式式测测试试 用例包含一整套单元测试,涵盖了各种可能的函数使用方式。

对于大型项目,要实现全覆盖可能很难。

 

一个断言 方法。断言方法用来核实得到的结果是否与期望的结果一致。

在这里,我们知道get_formatted_name() 应返回这样的姓名,即名和姓的首字母为大写,且它们之间有一个空格,因此我们期望formatted_name 的值为Janis Joplin。

可通过测试的函数:

import unittest


def get_formatted_name(first, last, middle=''):
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

只包含一个方法的测试用例:

import unittest


def get_formatted_name(first, last, middle=''):
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()


class NamesTestCase(unittest.TestCase):
    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name('janis', 'joplin', 'japan')
        self.assertEqual(formatted_name, 'Janis Japan Joplin')


unittest.main()

一个要测试的类:

unittest.TestCase中提供了很多断言方法:

assertEqual(a, b) 核实a == b
assertNotEqual(a, b) 核实a != b
assertTrue(x) 核实x 为True
assertFalse(x) 核实x 为False
assertIn(item , list ) 核实 item 在 list 中
assertNotIn(item , list ) 核实 item 不在 list 中

class AnonymousSurvey():
    def __init__(self, question):
        self.question = question
        self.responses = []

    def show_question(self):
        print(question)

    def store_response(self, new_response):
        self.responses.append(new_response)

    def show_results(self):
        print("Survey results:" + str(self.responses))

question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

my_survey.show_question()
print("Enter 'q' at any time to quit.\n")

while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)

print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

测试类:

import unittest


class TestAnonymousSurvey(unittest.TestCase):
    def test_store_response(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English', my_survey.responses)


unittest.main()

提供三个答案的测试:

import unittest

class TestAnonymousSurvey(unittest.TestCase):
    def setUp(self):
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']

    def test_store_single_response(self):
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_responses(self):
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)
            
unittest.main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值