zoukankan      html  css  js  c++  java
  • 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里面的语句块,这个程序中的作用是关掉文件

  • 相关阅读:
    ORM之F和Q
    ORM查询
    Django
    jQuery基础
    DOM和BOM
    saas baas paas iaas 的理解
    分布式架构的演进过程
    tomcat 配置https 证书
    idea 学习总结
    简单数据库连接池-总结
  • 原文地址:https://www.cnblogs.com/bovine/p/2262540.html
Copyright © 2011-2022 走看看