异常处理

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

def main():
    try:
        for line in readfile('lines.txt'): print(line.strip()) 
    except IOError as e:
        print('could not open the file:',e)
    except ValueError as e:
        print('bad filename:',e)    

def readfile(filename):
    if filename.endswith(".txt"):        
        fh = open(filename)
        return fh.readlines()
    else: raise ValueError("file must be ends with .txt")
        

if __name__ == "__main__": main()