九、文件和异常
1、读取文件中的数据
关键字with在不再需要访问文件后将其关闭;
相对文件路径
绝对文件路径:文件在系统中的完整路径;
with open('text_files\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
# 逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
# 包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line)
2、写入文件
(‘r’)读取模式, 默认
(‘w’)写入模式
(‘a’)附加模式,不覆盖文件,而把文件添加到文件末尾
(‘r+’)读取和写入模式
filename = 'pi_digits.txt'
with open(filename , 'w') as file_object:
file_object.write("test")
print(contents)
十、异常
使用异常对象来管理程序运行时发生的错误。程序崩溃时,出现traceback,显示错误信息;
使用try-except代码处理异常;
try:
answer = int(frist_number) / int(second_number)
except:
print("You can't divide by 0!")
else:
print(answer)
使用json存储数据
import json
numbers = [2, 3, 5, 7, 11]
filename = 'number.json'
# 存
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# 取
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
重构:将代码划分为一系列完成具体工作的函数的过程;
十一、测试代码
单元测试:用于核实函数的某个方面没有问题;
测试用例:一组单元测试,一起核实函数在各种情形下的行为都符合要求;
全覆盖式测试:用例包含一整套单元测试,涵盖了各种可能的函数使用方式。在项目中,最初可只针对代码中重要的行为编写测试,等项目广泛使用时再考虑全覆盖。
1、测试函数
import unittest
from name_function import get_formatted_name
class NameTestCase(unittest.TestCase): # 类的命名和要测试的函数相关,并包含Test,继承unittest.TestCase
"""测试name_function.py"""
def test_first_last_name(self): # 以test_ 开头
"""能正确地处理Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_nam('Janis', 'Joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
测试未通过时,如果检查的条件没错,意味着编写的新代码有错,应修改出错的代码;测试驱动开发;
2、测试类
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def setUp(self): # Python将先运行它,再运行各个以test_打头的方法
"""创建一个调查对象和一组答案,供使用的测试方法使用"""
pass
def test_store_single_response(self):
pass
def test_store_three_responses(self):
pass
unittest.main()