[关闭]
@chenwei123 2018-02-08T03:34:21.000000Z 字数 2787 阅读 471

文件和异常

Python


文件

1.从文件中读数据

  1. #file_reader.py
  2. with open('c.txt') as f:
  3. contents = f.read()
  4. for line in f:
  5. #逐行读取文件内容
  6. print(line)
  7. lines = f.readlines()
  8. for line in lines:
  9. print(line)

open()函数接受了一个参数:要打开的文件的名称。关键字 with 在不再需要访问文件后将其关闭。read()读取这个文件的全部内容。readlines()从文件中读取每一行,并将其存储在一个列表中。open('/Users/chen/test.txt', 'r', encoding='gbk', errors='ignore'),读取 gbk 编码的文件,遇到编码错误时忽略

2.写入文件

  1. with open('c.txt', 'w') as f:
  2. f.write("I love programming.")
  • open()函数接受两个参数:第一个是要打开的文件的名称,第二个是告诉 Python 写模式打开。可以指定的模式有:读('r')、写('w')、附加('a')、读和写('r+')。省略第二个参数,则默认是只读模式。
  • 如果给文件添加内容,而不是覆盖原有的内容,可以以附加模式打开文件。

异常

  1. try:
  2. print("123")
  3. except Exception:
  4. pass
  5. else:
  6. --snip--
  7. try:
  8. print("123")
  9. except Exception:
  10. pass
  11. else:
  12. --snip--

操作文件和目录

  1. import os
  2. os.name #操作系统类型
  3. os.uname() #详情的系统信息
  4. os.environ #环境变量
  5. os.environ.get('key') #获取某个环境变量的值
  6. os.path.abspath('.') #查看当前目录的绝对路径
  1. #在某个目录下创建一个新目录,首先把新目录的完整路径表示出来
  2. os.path.join('/Users/chen/Desktop/python3', 'testDir')
  3. #然后创建一个目录
  4. os.mkdir('/Users/chen/Desktop/python3/testDir')
  1. #删掉一个目录
  2. os.rmdir('/Users/chen/Desktop/python3/testDir')
  1. #拆分路径
  2. os.path.split('/Users/chen/Desktop/python3/hello.py') #('/Users/chen/Desktop/python3', 'hello.py')
  3. os.path.splitext('/Users/chen/Desktop/python3/hello.py') #('/Users/chen/Desktop/python3/hello', '.py')
  1. #对文件重命名
  2. os.rename('test.txt', 'test.py')
  1. #删掉文件
  2. os.remove('test.py')
  1. #列出当前目录下的所有目录:
  2. [x for x in os.listdir('.') if os.path.isdir(x)] #['config', 'demo']
  3. `os.listdir('.')`:当前目录下所有文件
  1. #列出当前目录下的所有.py 文件
  2. [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'] #['hello.py', 'IOCode.py']

存储数据 json

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

函数 json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。

  1. import json
  2. d = dict(name="Bob", age=20, score=80)
  3. json.dumps(d) #把一个对象变成 json 字符串。 '{"age": 20, "score": 88, "name": "Bob"}'
  1. import json
  2. filename = 'numbers.json'
  3. with open(filename) as f:
  4. numbers = json.load(f)
  5. print(numbers)

函数json.load()加载存储在 numbers.json 中的信息

  1. import json
  2. json_str='{"age": 20, "score": 88, "name": "Bob"}'
  3. json.loads(json_str) #把一个 json 字符串变成 json 对象。{'age': 20, 'score': 88, 'name': 'Bob'}

了解更多 json

测试用例 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.测试用例

  1. #name_function.py
  2. def get_formatted_name(first, last):
  3. full_name = first + " " + last
  4. return full_name.title()
  5. #test_name_function.py
  6. import unittest
  7. from name_function import get_formatted_name
  8. class NameTestCase(unittest.TestCase):
  9. def setUp(self):
  10. """创建一个调查对象,供使用的测试方法使用"""
  11. self.full_name = get_formatted_name("Chen", "Joe")
  12. def test_info(self):
  13. """要测试的方法"""
  14. self.assertEqual(self.full_name, "Chen Joe") #比较两者是否相等
  15. unittest.main() #运行文件中的测试
  • 首先导入测试用的模块 unittest 和要测试的函数 get_formatted_name,之后编写一个继承 unittest.TestCase 的类,类中包含以 test_开头的测试方法。之后运行test_name_function.py测试文件,所有以 test_打头的方法都将自动运行。
  • setUp():创建一个调查对象,在测试方法中可以直接使用这个实例
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注