Python 初体验(五)

  • python也有逻辑上的分行键\。类似MATLAB里面的…
  • input and output
#!/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 = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('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, # Notice comma to avoid automatic newline added by Python
f.close() # close the file
注意python打开文件时默认的打开方式是读打开
 
  • 异常
#!/usr/bin/python
# Filename: raising.py
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 expecting at least %d'
% (x.length, x.atleast)
else:
print 'No exception was raised.'

注意到exception是可以raise滴,这对增加程序的鲁棒性很有好处

#!/usr/bin/python
# Filename: finally.py
import time
try:
    f = file('poem.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print 'Cleaning up...closed the file'

python延时的方法,python发生exception时会执行finally里面的语句块,这个程序中的作用是关掉文件

原文地址:https://www.cnblogs.com/bovine/p/2262540.html