Pythone入门到实践-学习笔记-Day4

第十章 文件和异常

一、文件

  1. 读取文件
#例1:一次性读取
with open('pi_digits.txt')  as file_object:
    print(file_object.read())
with open('pi_digits.txt')  as file_object:
  for line in file_object
    print(line )
#运行结果:
3.1415926535
  8979323846
  2643383279
#例2:逐行读取
with open('pi_digits.txt')  as file_object:
  for line in file_object:
    print(line)
#运行结果:
3.1415926535

  8979323846

  2643383279
  • 用open()打开文件,用read()读取文件,用close()关闭文件,使用with open() 时,Python会自动close文件
    可使用相对路径(程序当前执行文件)和绝对路径
    因为每行后面有看不见换行符,所以逐行print时会把换行符打印出来
  1. 写入文件
filename='programming.txt'
with open(filename,'w') as file_objects:
  file_object.write('I love programming')

open()第二个实参(r,w,a,r+)分别代表读、写、附加、读写模式,如果省略第二个,默认只读模式打开
如果文件不存在,在写模式下函数open()会自动创建,但是,以写入('w')模式打开文件时,如果文件已经存在,Python将在返回文件对象前清空该文件
如果不想覆盖原有内容,可以使用附加模式('a')打开

异常

Python使用被称为异常的特殊对象来管理程序执行期间发生的错误,每当发生让Python不知所措的错误时,它都会创建一个异常对象,发果编写了处理该异常的代码,程序将继续运行,如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告
异常是使用try-except代码块处理的,try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办,程序继续运行,显示写好的错误信息,而不是traceback.

try:
  print(5/0)
except  ZeroDivisionError:
  print("You can't divide by zero")
#运行结果:
You can't divide by zero
#例2:
print("Give me two numbers,and I'll divide them")
print("Enter 'q' to quit")
while True:
  first_number=input("\nFirst Number:")
  if first_name='q':
    break
  second_number = input("\nSecond Number:")
  try:
    answer  = int(first_name) /  int(second_name)
  except:
    print("You can't divide by 0")
    #pass 表示什么都不做
  else:
    print(answer)
#运行结果:
Give me two numbers,and I'll divide them
Enter 'q' to quit

First Number:6

Second Number:3
2.0

First Number:6

Second Number:0
You can't divide by 0

First Number:q

异常:FileNotFoundError,ZeroDivisionError

存储数据(json)

import json
numbers = list(range(1,10))
filename = 'numbers.json'
with open(filename,'w') as file_obj:
  json.dump(numbers,file_obj)

#例2,读取numbers.json
import json
filename = 'numbers.json'
with open(filename) as file_obj:
  numbers= json.load(file_obj)
  print(numbers)

josn.dump()存储数据,json.load()读取数据

第十一章 测试代码

测试函数

def get_formatted_name(first,last):
  full_name = first + ' ' + last
  return full_name.title()  

import unittest

class NamesTestCase(unittest.TestCase):
  def test_name(self):
    full_name = get_formatted_name('Jimmy','liu')
    self.assertEqual(full_name,'Jimmy Liu');

unittest.main()
#运行结果:
Ran 1 test in 0.001s

OK

先导入unittest模块,然后创建一个类,用于包含一系列单元测试,这个类必继承unittest.TestCase类,这样Python才知道如何运行测试;
方法名必须以test_打头,这样它才会在运行时自动运行;
断言方法assertEqual,用来核实得到的结果是否与期望的结果一致

方法 用途
assertEqual(a,b) 核实a==b
assertNotEqual(a,b) 核实a!=b
assertTrue(x) 核实x为True
assertFalse(x) 核实a为False
assertIn(item,list) 核实item在list中
assertNotIn(a,b) 核实item不在list中

测试类

import unittest
class AnonymousSurvey():
  def __init__(self,question):
    self.question = question
    self.responses = []
  def show_question(self):
    print(question)
  def save_resp(self,resp): 
    self.responses.append(resp)
  def show_ressult(self):
    print('Survey List:')
    for resp in responses:
      print('- ' + resp)

class TestAnonmyousSurvey(unittest.TestCase):
  def setUp(self):
    question = "What language did you first learn to speck?"
    self.my_survey=AnonymousSurvey(question)
    self.my_survey.responses = ['English', 'Spanish', 'Mandarin'] 
    self.my_survey.save_resp('Chinese')   
    self.testresponses = ['English', 'Spanish', 'Mandarin'] 


  def test_save_single_resp(self):    
    self.assertIn('English',self.my_survey.responses)

  def test_all_resp(self):
    for resp in self.testresponses :
       self.assertIn(resp,self.my_survey.responses)
unittest.main()

Python会先运行setUp(),再运行test_开头的方法,在setUp()方法中创建一系列实例并设置他们的属性,再在测试法中直接使用这些实例。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第十章(二) 2、写入文件 保存数据的最简单的方式之一是将其写入到文件中。 (1)写入空文件 要将文本写入文件,需...
    晓梅_aa3b阅读 528评论 0 0
  • 接口测试自动化的优点: 1,web自动化说起来很多人都会直接想到UI自动化这个设计,很少有人直接第一个概念是接口自...
    路边看雪的小男孩阅读 4,951评论 1 26
  • python学习笔记 声明:学习笔记主要是根据廖雪峰官方网站python学习学习的,另外根据自己平时的积累进行修正...
    renyangfar阅读 3,087评论 0 10
  • 这几天回家的路上一直在看微信平台推送有关时间管理的文章,于是鸡血加了点,焦虑感神了些。 现在除了上午去学车,其他时...
    A大眼仔阅读 455评论 1 1
  • 感恩祖国的繁荣安定,让我们每天都能自由自在的做自己想做的事,感恩大自然给予的一切 感恩父母的养育之恩,感恩父母公婆...
    危志霞阅读 40评论 0 0