python学习--文件、标准库、异常处理

来源:互联网 发布:淘宝买枪暗语 编辑:程序博客网 时间:2024/05/21 22:51
#文件#touch read.txt#Welcome to this file#There is nothing here except#This stupid haiku#open()打开文件 read()读取文件f = open(r'./read.txt')print f.read(7)                #Welcomprint f.read(4)       # toprint f.read()                 #this file      读取剩下得文件,而不是从头开始读                               #There is nothing here except                               #This stupid haiku           #readline()读取一整行f = open(r'./read.txt')for i in range(3):    print str(i) + ': ' + f.readline(),f.close()   #return#0: Welcome to this file#1: There is nothing here except #2: This stupid haiku       #同时读取多行,以一个列表返回,每行是一个元素t = open(r'./read.txt')list = t.readlines()print list['Welcome to this file, There is nothing here except, This stupid haiku']#write()写入数据  注意要给read.txt写入得权限f = open(r'./read.txt', 'w')f.write('this\nis  no\nhaiku')f.close()         #修改文件f = open(r'./read.txt')lines = f.readlines()f.close()lines[1] = "isn't a\n"f = open(r'./read.txt', 'w')f.writelines(lines)f.close()#Welcome to this file#isn't a#This stupid haiku#按字节读取f=open(filename)while True:    char = f.read(1)    if not char: break    process(char)f.close()    #按行读取f=open(filename)while char:    line = f.readline()    if not line: break    process(line)f.close()#读取所有内容f=open(filename)for line in f.readlines():    process(line)f.close()#使用fileinput实现迭代,fileinput模块包含了一个打开文的函数,只需要传入一个文件名给它就可以import fileinputfor line in fileinput.input(filename):    process(line)
#标准库 #sys模块访问与python解析器相关的函数和变量 #os模块提供访问多个操作系统服务的功能  #fileinput模块可以轻松遍历整个文件 import fileinput                     for line in fileinput.input(inplace = True):              #inplace = True以原地处理,返回循环遍历对象                        line = line.rstrip()                                              #返回字符串副本的字符串方法,右侧的空格被删除                             num = fileinput.lineno()                                    #返回当前文件的行数    print '%-40s # %2i ' % (line, num)         #return  如下 import fileinput                         #  1 for line in fileinput.input(inplace = True): #  2                                        line = line.rstrip()                 #  3     num = fileinput.lineno()             #  4     print '%-40s # %2i ' % (line, num)   #  5   #heapq模块 堆from heapq import *from random import shuffledata = range(10)                              #产生10个随机数shuffle(data)heap = []for n in data:    heappush(heap, n)                        #元素循环入堆    print heapheappush(heap, 0.5)                         #插入元素0.5print heapprint heappop(heap)                        #弹出堆中最小元素print heapprint heapreplace(heap, 10)              #弹出堆中最小元素,同时插入元素print heap#双端队列 collections模块包含deque类型from collections import dequeq = deque(range(5))print qq.append(5)         #右边追加q.appendleft(8)    #左边追加print qprint q.pop()      #右边弹出print q.popleft()   #左边弹出#random模块from random import *d = uniform(1, 10)      #返回随机实数n,其中a到bprint dseq = range(10)        print seqprint choice(seq)        #从序seq列中返回随意元素print sample(seq, 3)   #从序seq列中返回n个随机独立元素print randrange(2, 8, 1)  #返回序列中range(start, stop, step)中的随机数
#异常处理#使用空的except子句来捕获所有Exception类的异常,无论try子句中是否发生异常,finally语句都会执行 while True:    try:        x = input('Enter the first number: ')        y = input('Enter the second number: ')        value = x/y        print 'x/y is',value    except Exception,e:        print 'Invalid input:',e        print 'please try again'    else:        print "good"    finally:        print "cleaning up!"        #return #Enter the first number: 1#Enter the second number: 0#Invalid input: integer division or modulo by zero   #会有错误提示#please try again#cleaning up!#Enter the first number: 12#Enter the second number: 2#good#cleaning up!#重要异常Exception: 所有异常AttributeErro; 特性引用或赋值失败引发IOError:  试图打开不存在的文件IndexError:  使用序列中不存在的索引引发 KeyError:   在使用映射中不存在的键引发NameError:  找不到名字引发SyntaxError:  代码错误引发TypeError:    在内建操作或者函数应用于错误的对象时引发ValueError:   对象使用不合适的值引发ZeroDivisionError: 除法或模除操作第二个参数为0引发

原创粉丝点击