您的位置:首页 > 编程语言 > Python开发

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

2017-08-04 10:18 316 查看
#文件
#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)                #Welcom
print f.read(4)		       # to
print 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 fileinput
for 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 shuffle
data = range(10)                              #产生10个随机数
shuffle(data)
heap = []
for n in data:
    heappush(heap, n)                        #元素循环入堆    
print heap

heappush(heap, 0.5)                         #插入元素0.5
print heap

print heappop(heap)                        #弹出堆中最小元素
print heap

print heapreplace(heap, 10)              #弹出堆中最小元素,同时插入元素
print heap

#双端队列 collections模块包含deque类型
from collections import deque
q = deque(range(5))
print q

q.append(5)         #右边追加
q.appendleft(8)    #左边追加
print q
print q.pop()      #右边弹出
print q.popleft()   #左边弹出

#random模块
from random import *
d = uniform(1, 10)      #返回随机实数n,其中a到b
print d

seq = range(10)        
print seq

print 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引发
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: