Byte of Python学习笔记六

来源:互联网 发布:数据采集软件101data 编辑:程序博客网 时间:2024/05/16 03:32
十一. 输入输出
1. 交互解释器输入输出
>>>number= input('Enter a number:')
Enter a number:1
>>>print(number)
输入通过input()函数,可以接受一个字符串,作为提示信息输出,等待并用户输入,并将输入内容作为函数的返回值返回。
输出通过print()函数,具体用法参考help(print)

2.文件读写
Python中通过open函数打开文件,创建file类对象,然后调用file类对象的read,readline或write方法来读写文件。
打开文件时可以指定打开模式:读模式('r'), 写模式('w'), 追加模式('a'); 还能指定文件处理方式:文本文件('t'),二进制文件('b');默认为读模式,处理方式为文本文件,详细信息参考help(open)。
注意:文件对象使用完毕,需要调用close方法将文件关闭,避免内存泄漏。
#!/usr/bin/python
# Filename: using_file.py
 
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
''' 
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
 
f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed 
by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print(line, end='')
f.close() # close the file
该程序先打开文件poem.txt 然后将字符串poem写入到文件,然后逐行读取文件输出

3. 对象序列化/反序列化
Python提供了标准模块pickle帮助进行对象序列化
(1) 对象序列化
shoplist=['apple', 'mango', 'carrot']
f = open('shoplist.data', 'wb') #以二进制写方式打开存贮对象文件
pickle.dump(shoplist, f) #将对象写入文件
f.close()

(2)对象反序列化
f = open('shoplist.data', 'rb') #以二进制读方式打开文件
shoplist = pickle.load(f) # 从文件读入对象
f.close()

十二. 异常
1. 异常处理
Python通过try..except..finally..else...语句处理异常,其中finally和else可以没有。如
try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {0}'.format(text))
说明:
(1) 每个try后面必须至少有一个except语句,except后面可以跟一个或多个异常名,多个异常以元组形式出现;也可以没有异常名,表示出处理所有异常。
(2) else语句在没有异常信息时执行
(3) finally语句不管是否出现异常都要执行

3. 自定义异常
自定义异常继承Exception类,如:
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
    # Other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print('ShortInputException: The input was {0} long, expected at 
least {1}'\
          .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')
该程序自定义异常ShortInputException继承Exception,自定义异常可以像Python内建异常一样使用
说明:
(1) 上面程序中抛出异常使用raise关键字,后跟需要抛出的异常对象
raise ShortInputException(len(text), 3)
(2) 上面程序中except ShortInputException as ex语句使用了as关键字,后跟变量名,接受程序抛出的ShortInputException类对象,通过该变量ex可以获取信息

with语句
with用来处理获取资源,最后是否资源的情况,避免写负责的try..except..finally..语句,with语句能够自动进行资源的释放,是我们的只需要关注资源的处理逻辑,如
with open("poem.txt") as f:
    for line in f:
        print(line, end='')
该程序读取poem.txt文件,然后逐行输出。
with语句深度了解请参考http://www.python.org/dev/peps/pep-0343/

原创粉丝点击