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

  • 相关阅读:
    设计模式-转载
    Java-类和对象基础练习
    Java-单例模式(singleton)-转载
    java-面向对象练习2
    Java-面向对象基础练习
    Java-字符串练习
    Java-数组练习5
    Java-数组练习4
    JAVA-初步认识-常用对象API(String类-常见功能-获取-1)
    JAVA-初步认识-常用对象API(String类-构造函数)
  • 原文地址:https://www.cnblogs.com/bovine/p/2262540.html
Copyright © 2020-2023  润新知