文件读取
'''读取内容'''
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() # 运行所有的测试用例