现在的位置: 首页 > 综合 > 正文

So cute are you python 7

2013年12月08日 ⁄ 综合 ⁄ 共 2314字 ⁄ 字号 评论关闭

1.Python using file 。

#!/usr/bin/evn python
#coding:utf-8
#FileName:using_file.py
#function:Show how to use python to operation a file simply.
#History:12-10-2013
poem ='''\
Programing is fun
When the work is done
if you wanna make your work also fun:
     Using python!
'''
f = file('poem.txt','w')#open a file for writing.
f.write(poem)#Write text to file
f.close()#close the file.
 
f =file('poem.txt')
#if no mode os specified,'r'ead mode is assumed by default.
while True:
    line=f.readline()
    if len(line)== 0:
        #print 'No contents on poem.txt'
        break
    print line,
    # Notice comma to avoid automatic newline aded by python
f.close()#close the file.

2.using pickle with oython

#!/usr/bin/evn python
#coding:utf-8
#FileName:pickling.py
#function:Show how to use python to pickling things with cPickle module
#then read back from the storage
#History:12-10-2013
import cPickle as p
#import pickle module
shoplistfile ='shoplist.data'
#the name of the file where we will store the object
 
shoplist = ['apple','mange','carrat']
 
#write to the file
f =file(shoplistfile,'w')
p.dump(shoplist,f)#dump the object to a file
f.close()
 
del shoplist #remove the sjoplist
 
#read back from the storage
f=file(shoplistfile)
storedlist=p.load(f)
print storedlist

3.Catch Exceptions

#!/usr/bin/evn python
#coding:utf-8
#FileName:try_except.py
#function:Show how to use python to catch exceptios and deal with it.
#History:12-10-2013
 
import sys
 
try:
    s=raw_input('Enter something-->')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit()#Exit the program.
except:
    print '\nSome error/exception occurred.'
    #here,we are not exiting the program
 
print 'Works Done!\r\n'

4.Using raising

#!/usr/bin/evn python
#coding:utf-8
#FileName:raising.py
#function:Show how to use python to catch exceptions by using raising
 
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast
 
try:
    s=raw_input('Enter something-->')
    if len(s)< 3:
        raise ShortInputException(len(s), 3)
    #other work can continue as usual here
except EOFError:
    print '\nWhy did you do an EOF on me ?'
except ShortInputException,x:
    print 'ShortInputException:The input was of length %d,\
           was excepting at least %d'%(x.length,x.atleast)
else:
    print 'No exception was raised.'

5.Using finally

#!/usr/bin/evn python
#coding:utf-8
#FileName:finally.py
#function:Show how to use python to Using try finally
#history:12-10-2013
import time
 
try:
    f=file('poem.txt')
    while True:
        line =f.readline()
        if len(line)== 0:
            break
        time.sleep( 2)
        print line,
finally:
    f.close()
    print 'Cleaning up...closed the file.'

抱歉!评论已关闭.