#-*- coding:utf-8 -*-
'''
Created on 2011-12-4
作者: 李昱彤
Email: liqi1031@gmail.com
'''
#open 函数可能引发IOError异常(可能文件不存在)
#seek 方法可能引发IOError异常(可能是文件长度小于给定的字节数)
#read 方法可能引发IOError异常(可能磁盘有坏扇区,或它在一个网络驱动器上,而网络刚好断了)
'''
Created on 2011-12-4
作者: 李昱彤
Email: liqi1031@gmail.com
'''
#open 函数可能引发IOError异常(可能文件不存在)
#seek 方法可能引发IOError异常(可能是文件长度小于给定的字节数)
#read 方法可能引发IOError异常(可能磁盘有坏扇区,或它在一个网络驱动器上,而网络刚好断了)
#import pdb
#pdb.set_trace()
filename = "d:\python27\python.exe"
#pdb.set_trace()
filename = "d:\python27\python.exe"
#计算文件的大小
f = open(filename, "rb", 0)
fileStart = f.tell()
print "file start position: ", fileStart, "byte"
f.seek(0,2)
fileEnd =f.tell()
print "file end position: ", fileEnd, "bytes"
print "So file size is ", (fileEnd - fileStart), "bytes."
f = open(filename, "rb", 0)
fileStart = f.tell()
print "file start position: ", fileStart, "byte"
f.seek(0,2)
fileEnd =f.tell()
print "file end position: ", fileEnd, "bytes"
print "So file size is ", (fileEnd - fileStart), "bytes."
#引发seek异常
try:
f = open(filename,"rb", 0)
try:
print "file pointer position is ", f.tell()
f.seek(-26625,2)
data = f.read(10)
print "getting 10 bytes file content is ", data
print "file pointer position is ", f.tell()
finally:
f.close()
except IOError:
print 'IOError from f.seek() happens'
try:
f = open(filename,"rb", 0)
try:
print "file pointer position is ", f.tell()
f.seek(-26625,2)
data = f.read(10)
print "getting 10 bytes file content is ", data
print "file pointer position is ", f.tell()
finally:
f.close()
except IOError:
print 'IOError from f.seek() happens'
输出结果:
file start position: 0 byte
file end position: 26624 bytes
So file size is 26624 bytes.
file pointer position is 0
IOError from f.seek() happens
file end position: 26624 bytes
So file size is 26624 bytes.
file pointer position is 0
IOError from f.seek() happens