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

程序一:
1 2 3 4 5 6 7 8 9 10 11 12 | 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
程序二:
1 2 3 4 5 6 7 8 9 10 11 | 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
程序三:
1 2 3 4 5 6 7 8 9 10 11 12 | 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为什么有tcl
Python软件收费吗
Python变量类型-Python字符串str()的用法(示例)
Python使用dir函数查看类中所有成员的方法介绍
Python读取文本中数据并转化为dataframe的实例_Python
如何访问Python字典里的值?(实例解析)
Python如何判断变量是否是整数
Python是什么?
Python中print与return区别
Python工作好找吗
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python读取文件内容的三种方式与效率比较的详解