文件和异常
文件
1.从文件中读数据
#file_reader.py
with open('c.txt') as f:
contents = f.read()
for line in f:
#逐行读取文件内容
print(line)
lines = f.readlines()
for line in lines:
print(line)
open()
函数接受了一个参数:要打开的文件的名称。关键字 with 在不再需要访问文件后将其关闭。read()
读取这个文件的全部内容。readlines()
从文件中读取每一行,并将其存储在一个列表中。open('/Users/chen/test.txt', 'r', encoding='gbk', errors='ignore')
,读取 gbk 编码的文件,遇到编码错误时忽略
2.写入文件
with open('c.txt', 'w') as f:
f.write("I love programming.")
open()
函数接受两个参数:第一个是要打开的文件的名称,第二个是告诉 Python 写模式打开。可以指定的模式有:读(’r’)、写(’w’)、附加(’a’)、读和写(’r+’)。省略第二个参数,则默认是只读模式。- 如果给文件添加内容,而不是覆盖原有的内容,可以以附加模式打开文件。
异常
try:
print("123")
except Exception:
pass
else:
--snip--
try:
print("123")
except Exception:
pass
else:
--snip--
操作文件和目录
- 系统信息
import os
os.name #操作系统类型
os.uname() #详情的系统信息
os.environ #环境变量
os.environ.get('key') #获取某个环境变量的值
os.path.abspath('.') #查看当前目录的绝对路径
- 创建目录
#在某个目录下创建一个新目录,首先把新目录的完整路径表示出来
os.path.join('/Users/chen/Desktop/python3', 'testDir')
#然后创建一个目录
os.mkdir('/Users/chen/Desktop/python3/testDir')
- 删除目录
#删掉一个目录
os.rmdir('/Users/chen/Desktop/python3/testDir')
- 拆分路径
#拆分路径
os.path.split('/Users/chen/Desktop/python3/hello.py') #('/Users/chen/Desktop/python3', 'hello.py')
os.path.splitext('/Users/chen/Desktop/python3/hello.py') #('/Users/chen/Desktop/python3/hello', '.py')
- 文件重命名
#对文件重命名
os.rename('test.txt', 'test.py')
- 删掉文件
#删掉文件
os.remove('test.py')
- 列出当前目录下所有目录
#列出当前目录下的所有目录:
[x for x in os.listdir('.') if os.path.isdir(x)] #['config', 'demo']
`os.listdir('.')`:当前目录下所有文件
- 列出当前目录下所有
.py
文件
#列出当前目录下的所有.py 文件
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'] #['hello.py', 'IOCode.py']
存储数据 json
- 存储 json 数据
import json
numbers = [1,2,3,7,11,13]
filename = 'numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
函数
json.dump()
接受两个实参:要存储的数据以及可用于存储数据的文件对象。
import json
d = dict(name="Bob", age=20, score=80)
json.dumps(d) #把一个对象变成 json 字符串。 '{"age": 20, "score": 88, "name": "Bob"}'
- 加载 json 数据
import json
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)
print(numbers)
函数
json.load()
加载存储在 numbers.json 中的信息
import json
json_str='{"age": 20, "score": 88, "name": "Bob"}'
json.loads(json_str) #把一个 json 字符串变成 json 对象。{'age': 20, 'score': 88, 'name': 'Bob'}
测试用例 unittest
1.unittest 断言方法
方法 | 用途 |
---|---|
assertEqual(a,b) | 核实 a==b |
assertNotEqual(a,b) | 核实a!=b |
assertTrue(x) | 核实 x 为 True |
assertFalse(x) | 核实 x 为 False |
assertIn(item, list) | 核实 item在 list 中 |
assertNotIn(item, list) | 核实 item 不在 list 中 |
2.测试用例
#name_function.py
def get_formatted_name(first, last):
full_name = first + " " + last
return full_name.title()
#test_name_function.py
import unittest
from name_function import get_formatted_name
class NameTestCase(unittest.TestCase):
def setUp(self):
"""创建一个调查对象,供使用的测试方法使用"""
self.full_name = get_formatted_name("Chen", "Joe")
def test_info(self):
"""要测试的方法"""
self.assertEqual(self.full_name, "Chen Joe") #比较两者是否相等
unittest.main() #运行文件中的测试
- 首先导入测试用的模块
unittest
和要测试的函数get_formatted_name
,之后编写一个继承unittest.TestCase
的类,类中包含以test_
开头的测试方法。之后运行test_name_function.py
测试文件,所有以test_
打头的方法都将自动运行。setUp()
:创建一个调查对象,在测试方法中可以直接使用这个实例