这篇文章主要介绍了python读取文件内容的三种常用方式及效率比较,结合具体实例形式给出了三种文件读取的常见方法并对比分析了读取速度,需要的朋友可以参考下
本文实例讲述了Python读取文件内容的三种常用方式。分享给大家供大家参考,具体如下:
本次实验的文件是一个60M的文件,共计392660行内容。

程序一:
立即学习“Python免费学习笔记(深入)”;
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读取文件内容的三种方式与效率比较的详解的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号