(四)python学习笔记之文件读写,异常处理,JSON,测试类

文件读取

'''读取内容'''
with open("data/tt.txt") as file:
    contents=file.read()
    print(contents)
'''读取列表'''
with open("data/tt.txt") as file:
    contents=file.readlines()
    for content in contents:
        print(content)
'''写入信息'''
with open("data/tt.txt",'w') as file:	#注意打开方式为写方式
    file.write("I love you.")
'''在文件尾部写入信息'''
with open("data/tt.txt",'a') as file:	#注意设置文件打开方式为尾部写入
    file.write("I love you.")
    file.write("I love you.")

异常处理

'''除数为零异常'''
try:
    print(5/1)
except ZeroDivisionError:
    print("error")
else:
    print("success")
'''文件未找到异常'''
try:
    with open("data/tt.txt") as file:
        contents=file.read()
except FileNotFoundError:
    print("File not found!")
else:
    print(contents)

JSON

'''向文件写入json数据1'''
import json
numbers = [1, 2, 3]
with open("JSONTest.json","w") as file:
    json.dump(numbers,file)
'''向文件写入json数据2'''
import json
numbers = "111"
with open("JSONTest.json","w") as file:
    json.dump(numbers,file)
'''读取JSON数据'''
import json
numbers = [1, 2, 3]
with open("JSONTest.json") as file:
    numbers=json.load(file)
print(numbers)

测试类

import unittest


class MyTest(unittest.TestCase):  # 继承unittest.TestCase
    def tearDown(self):
        # 每个测试用例执行之后做操作
        print('111')

    def setUp(self):
        # 每个测试用例执行之前做操作
        print('22222')

    @classmethod
    def tearDownClass(self):
        # 必须使用 @ classmethod装饰器, 所有test运行完后运行一次
        print('4444444')

    @classmethod
    def setUpClass(self):
        # 必须使用@classmethod 装饰器,所有test运行前运行一次
        print('33333')

    def test_a_run(self):
        self.assertEqual(1, 1)  # 测试用例

    def test_b_run(self):
        self.assertEqual(2, 2)  # 测试用例


if __name__ == '__main__':
    unittest.main()  # 运行所有的测试用例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值