@chenwei123
2018-02-08T03:34:21.000000Z
字数 2787
阅读 471
Python
#file_reader.pywith 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 编码的文件,遇到编码错误时忽略
with open('c.txt', 'w') as f:f.write("I love programming.")
open()函数接受两个参数:第一个是要打开的文件的名称,第二个是告诉 Python 写模式打开。可以指定的模式有:读('r')、写('w')、附加('a')、读和写('r+')。省略第二个参数,则默认是只读模式。- 如果给文件添加内容,而不是覆盖原有的内容,可以以附加模式打开文件。
try:print("123")except Exception:passelse:--snip--try:print("123")except Exception:passelse:--snip--
import osos.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']
import jsonnumbers = [1,2,3,7,11,13]filename = 'numbers.json'with open(filename, 'w') as f:json.dump(numbers, f)
函数
json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。
import jsond = dict(name="Bob", age=20, score=80)json.dumps(d) #把一个对象变成 json 字符串。 '{"age": 20, "score": 88, "name": "Bob"}'
import jsonfilename = 'numbers.json'with open(filename) as f:numbers = json.load(f)print(numbers)
函数
json.load()加载存储在 numbers.json 中的信息
import jsonjson_str='{"age": 20, "score": 88, "name": "Bob"}'json.loads(json_str) #把一个 json 字符串变成 json 对象。{'age': 20, 'score': 88, 'name': 'Bob'}
| 方法 | 用途 |
|---|---|
| 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 中 |
#name_function.pydef get_formatted_name(first, last):full_name = first + " " + lastreturn full_name.title()#test_name_function.pyimport unittestfrom name_function import get_formatted_nameclass 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():创建一个调查对象,在测试方法中可以直接使用这个实例