python_day_03(文件、异常以及测试)

文件打开:

with open('test.txt') as file_object:  //
contents= file_object.read()
print(contents.rstrip()) //rstrip表示去除content的空格

文件写入

filename='test.txt'
with open(filename,'w') as file_object:// 'w'表示直接覆盖之前的内容 'a'表示的附加到之前的内容
file_object.write('I love programme.\n')
file_object.write('I love creating new game.\n')

异常处理;

try:
print(5/0)
except ZeroDivisionError:

print("you can't devide by zero")


try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError://文件类处理异常
msg="Sorry, the file"+filename+"does not exist."

print(msg)



def count_words(filename):
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
pass  //当报错不想有任何提示的时候,就用pass
else:
words=contents.split();
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")


filenames=['test.txt','guest.txt','guest_book.txt','a.txt']
for file in filenames:
count_words(file)



import json
numbers=[2,3,5,7,9]
filename='numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object)//json.dump表示的是把对象写入到文件中


filename='numbers.json'
with open(filename) as f_obj:
number=json.load(f_obj)//json.load表示的是把文件写入对象

print(number)


测试函数:


import unittest

from pizza import get_formatted_name


class NameTestCase( unittest.TestCase):/ /所有的测试类都必须继承自unittest.TestCase
def test_first_last_name(self):
formatted_name=get_formatted_name('janis','joplin')

self.assertEqual(formatted_name,'Janis Joplin')//assertEqual表示的是判断对象和预期的测试结果是否一致

unittest.main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值