[A byte of Python] 学习笔记三

目录

输入与输出

用户输入内容input()

处理文件

Pickle

异常

处理异常

try...except语句

抛出异常

try...finally语句


输入与输出

用户输入内容input()

def reverse(text):
    return text[::-1]

def is_palindrom(text):
    return text == reverse(text)

something = input('Enter text: ')

if is_palindrom(something):
    print('Yes, it is a palindrom')
else:
    print('No, it is not a palindrom')
Enter text: sir
No, it is not a palindrom

Enter text: madam
Yes, it is a palindrom

处理文件

在默认情况下,open()函数将文件视为文本文件,并以阅读模式打开文件。

可选模式:阅读模式( 'r' ) , 写入模式( 'w' ) 和追加模式( 'a' ) 。 我们还可以选择是通过文本模式( 't' ) 还是二进制模式( 'b' ) 来读取、 写入或追加文本。

下例中对文件对象使用了write方法、close方法与readline方法。

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''

f = open('poem.txt', 'w')
f.write(poem)
f.close()

f = open('poem.txt')
while True:
    line = f.readline()
    if len(line) == 0:
        break
    print(line, end=' ')
f.close()
Programming is fun
 When the work is done
 if you wanna make your work also fun:
 use Python!

Pickle

通过Pickle标准模块可以将任何纯 Python 对象存储到一个文件中, 并在稍后将其取回,从而实现持久地( Persistently) 存储对象。

下例中调用了pickle模块的dump函数,这一过程称作封装(pickling)和load函数,这一过程则称作拆封(unpickling)。

import pickle

shoplistfile = 'shoplist.data'
shoplist = ['apple', 'orange', 'banana']

f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f)
f.close()

del shoplist

f = open(shoplistfile, 'rb')
storelist = pickle.load(f)
print(storelist)
['apple', 'orange', 'banana']

异常

处理异常

try...except语句

为了不在异常发生时结束程序,使用try语句块检测程序中的错误,从而让except语句捕获异常信息并处理。

  • 如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。
  • 如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印默认的出错信息)。
  • 如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。
# 去掉testfile的写入权限
chmod -w testfile

try:
    f = open("testfile", "w")
    f.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    f.close()
$ python test.py 
Error: 没有找到文件或读取文件失败

抛出异常

可以通过raise语句来引发异常, 具体方法是提供错误名或异常名以及要抛出( Thrown) 异常的对象。引发的错误或异常必须是直接或间接从属于 Exception ( 异常) 类的派生类。

class ShortInputException(Exception):
    def __init__(self, length, atleast):
        self.length = length
        self.atleast = atleast

try:
    text = input('Please enter something: ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
except EOFError:
    print('Why did you do me an EOFError?')
except ShortInputException as ex:
    print('The length of the text is {}, expected at least {}'.format(ex.length, ex.atleast))
else:
    print('No exception was raised.')
Please enter something: a
The length of the text is 1, expected at least 3

try...finally语句

try-finally 语句无论是否发生异常都将执行finally块的代码。常用于关闭try块中打开的文件。

try:
    fh = open("testfile", "w")
    try:
        fh.write("这是一个测试文件,用于测试异常!!")
    finally:
        print "关闭文件"
        fh.close()
except IOError:
    print "Error: 没有找到文件或读取文件失败"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值