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

Python读取文件内容的三种常用方式及效率比较

2017-10-07 18:53 931 查看

本次实验的文件是一个60M的文件,共计392660行内容。

程序一:

def one():
start = time.clock()
fo = open(file,'r')
fc = fo.readlines()
num = 0
for l in fc:
tup = l.rstrip('\n').rstrip().split('\t')
num = num+1
fo.close()
end = time.clock()
print end-start
print num

运行结果:0.812143868027s

程序二:

def two():
start = time.clock()
num = 0
with open(file, 'r') as f:
for l in f:
tup = l.rstrip('\n').rstrip().split('\t')
num = num+1
end = time.clock()
times = (end-start)
print times
print num

运行时间:0.74222778078

程序三:

def three():
start = time.clock()
fo = open(file,'r')
l = fo.readline()
num = 0
while l:
tup = l.rstrip('\n').rstrip().split('\t')
l = fo.readline()
num = num+1
end = time.clock()
print end-start
print num

运行时间:1.02316120797

由结果可得出,程序二的速度最快。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python URL操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 读取 文件