Python从入门到实践 学习笔记4

1.文件

读取文本文件时,Python将其中的所有文本都解读为字符串。如果读取的是数,并要将其作为数值使用,必须使用函数int()将其转化为整数或使用函数float()将其转化为浮点数。

#打开并读取文件
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents.rstrip()) #删除文件末尾多出来的空行(read()到达文件末尾时返回一个空字符串)

#逐行读取
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)
#输出每行后面都有一个空行

#在with代码块中将文件的各行存储在一个列表中,并在with代码块外使用该列表
with open(filename) as file_object:
    lines = file_object.readlines()

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

#使用文件的内容
pi_string = ''
for line in lines:
    pi_string += line.strip()
print(pi_string)
print(len(pi_string))

#圆周率值中包含你的生日吗
birthday = input("Enter your birthday,in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first millon digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi.")

#写入文件
filename = 'programming.txt'

with open(filename,'w') as file_object:     #写入模式
    file_object.write("I love programming")
    file_object.write("I love creating new games")

with open(filename,'a') as file_object:     #附加模式
    file_object.write("I also love finding meaning in large datasets.")
    file_object.write("……")

#处理ZeroDivisionError异常(使用try-except else代码块)
while True:
    first_name = input("\nFirst number: ")
    if first_name == 'q':
        break
    second_name = imput("Second number: ")
    if second_name == 'q':
        break
    try:
        answer = int(first_name)/int(second_name)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

#处理FileNotFoundError异常
file_name = '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()  #方法split()能根据一个字符串创建一个单词列表
    num-words = len(words)
    print(f"The file {filename} has about {num_words} words.")

#静默失败(pass)
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        --snip--
    except FileNotFoundError:
        pass
    else:
        --snip--

#存储数据
#使用json.dump()和json.load()
import json
numbers = [2,3,5,,7,11,13]
filename = "numbers.json'  #存储
with open(filename,'w') as f:
    json.dump(numbers,f)

with open(filename) as f:
    numbers = json.load(f) #读取

2.测试函数

方法名必须以test_打头,这样它才会在我们运行test_name_function.py时自动运行。

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.Testcase):  #NameTestCase类必须继承unittest.TestCase类
    """测试name_function.py。"""

    def test_first_last_name(self):
        """能够正确处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis Joplin') #断言方法

if _name_ == '_main_':
    unittest.main()
#如果该文件作为主程序执行,变量_name_将被设置为'_main_'。在这里,调用unittest.main()来运行
#测试用例。如果该文件被测试框架导入,变量_name_的值将不是'_main_',因此不会调用
#unittest.main()。

3.测试类

unittest模块中的断言方法

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

unittest.Testcase类包含的方法setUp()让我们只需创建这些对象一次,就能在每个测试方法中使用。

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试。"""

    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_response(self):
        """测试三个答案会被妥善地存储"""
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response,self.my_survey.responses)

2022/7/7 Python基础知识止

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值