《Python编程从入门到实践》学习笔记——第10-11章【2022.08.10】

第一部分 基础知识

第10章 文件和异常

第11章 测试代码

# 2022.08.10 by zgw

'''   第十章 文件和异常   '''

# 10.1 从文件中读取信息
print("\n-------- 10.1 -----\n")

'''
#pi.txt

3.1415926358979323846
'''

'''
另一种写法
import  os
path = os.path.join(os.path.dirname(__file__), "pi.txt")
with open(path) as file_object:
'''

#读取整个文件
with open('pi.txt') as file_object:
    texts = file_object.read()
print(texts)

#逐行读取
filename = 'pi.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip()) #使用rstrip去掉文本行末的换行

#创建一个包含文件各行内容的列表
filename ='pi.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

#使用文件内容
filename ='pi.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
pi_str = ''
for line in lines:
    pi_str += line.strip() #去除两端空格
print(pi_str)

# 10.2 写入文件
print("\n-------------- 10.2 写入文件 ------------\n")

filename = 'program.txt'
with open(filename, 'w') as file_object:    # r 读, w 写, a 附加, r+ 读写, 默认只读
    file_object.write("I love this game.\n")
    file_object.write("I love Python.\n")

#注意:Python只能将字符串写入文本文件。
#注意:以写入模式("w")打开文件时,如果文件已经存在,Python将在返回文件对象前,清空该文件的内容。

filename = 'program.txt'
with open(filename, 'a') as file_object:    # r 读(默认只读), w 写(注意:会覆盖已存在同名文件), a 附加, r+ 读写,
    file_object.write("I love C++.\n")
    file_object.write("I love Java.\n")

# 10.3 异常
print("\n------------------ 10.3 异常 -------------------\n")

print("输入两个整数,输出除法结果\n")
print("输入'q'退出")

while True:
    first_number = input("\n first number: ")
    if first_number == 'q':
        break
    second_number = input("\n second number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("除数不能为零!")
    else:
        print(answer)

print("\n-----------exam 2 ----------\n")

def count_words(filename):
    #计算一个文件大致含有多少个单词
    try:
        with open(filename,encoding='utf-8') as f:
            contens = f.read()
    except:
        print(f"文件 {filename} 不存在!")
        #pass       #pass不会显示错误提示,也可以理解为占位符
    else:
        words = contens.split()
        num_words = len(words)
        print(f"文件 {filename} 大致有 {num_words} 个单词。\n")

filenames = ['alice.txt', 'sid.txt', 'moby.txt', 'little.txt']
for filename in filenames:
    count_words(filename)

# 10.4 存储数据
print("\n-------- 10.4 存储数据 -------------\n")

import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f:
    json.dump(numbers,f)

import json
filename1 = 'numbers.json'
with open(filename1) as f:
    numbers1 = json.load(f)
print(numbers1)

print('\n---------------------重构---------------\n')

import json
def get_store_usename():
    '''如果存储用户名,就获取他'''
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
       return  None
    else:
        return username

def greet_user():
    """问候用户,并指出名字"""
    username = get_store_usename()
    if username:
        print(f"您的名字是:{username}")
    else:
        username = input("你的名字是: ")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dummp(username, f)
            print(f"欢迎回来,{username}")

greet_user()


'''  第十一章 测试代码   '''

#11.1 测试函数
print("\n----------------- 11.1 测试函数----------------------\n")

import unittest

def get_formatted_name(first, last, middle = ''):
    if middle:
        full_name = f"{first} {middle} {last}"
    else:
        full_name = f"{first} {last}"
    return full_name.title()

class NameTestCase(unittest.TestCase):
    #测试函数的类

    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name('zhao','king', 'guang' )
        self.assertEqual(formatted_name,"Zhao Guang King")

if __name__ == '__main__':
    unittest.main()

#11.2 测试类
print("----------------- 11.2 测试类 ---------------")

import  unittest
class AnonymousSurvey:
    '''收集匿名调查问卷了答案'''

    def __init__(self, question):
        """存储一个问题,并为存储答案做准备"""
        self.question = question
        self.respones = []

    def show_question(self):
        """显示调查问卷"""
        print(self.question)

    def store_response(self, new_respone):
        """存储单份调查答案。"""
        self.respones.append(new_respone)

    def show_reslut(self):
        '''显示收集到的所有答案'''
        print('收集的结果:')
        for respone in self.respones:
            print(f"- {respone}")

class TestAS(unittest.TestCase):
    '''针对AS类的测试'''
    def test_store_single_response(self):
        question = "你学的第一种语言是?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('chinese')
        self.assertIn('chinese', my_survey.respones)
if __name__ == '__main__':
    unittest.main()

# 11.2.3 方法setUp()  (略)

你可能感兴趣的:(python学习笔记,Python,python,学习,开发语言)