Python读取文件内容的三种常用方式及效率比较
作者:林六天 时间:2023-08-29 23:46:00
本文实例讲述了Python读取文件内容的三种常用方式。分享给大家供大家参考,具体如下:
本次实验的文件是一个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程序设计有所帮助。
来源:http://www.cnblogs.com/6tian/p/5886284.html
标签:Python,读取,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL UPDATE 语句的非标准实现代码
2024-01-16 19:08:57
关于keras中的Reshape用法
2021-11-08 00:04:12
CentOS 6.4下编译安装MySQL5.6.14教程
2024-01-20 01:06:43
Sublime Text 配置 Python 环境的问题及解决方案
2022-04-26 15:14:41
python 执行函数的九种方法
2021-03-10 18:12:08
php之php.ini配置文件讲解案例
2023-06-11 18:19:06
如何用VScode配置Python开发环境
2021-10-23 11:00:51
![](https://img.aspxhome.com/file/2023/5/115815_0s.gif)
Golang中slice删除元素的性能对比
2024-05-05 09:33:03
Pytest+Request+Allure+Jenkins实现接口自动化
2021-04-09 13:50:44
![](https://img.aspxhome.com/file/2023/3/112593_0s.png)
python读写文件with open的介绍
2022-04-03 22:19:34
![](https://img.aspxhome.com/file/2023/8/92458_0s.png)
详解Python中的__getitem__方法与slice对象的切片操作
2022-04-26 19:54:55
举例讲解Python中metaclass元类的创建与使用
2023-12-11 23:06:57
![](https://img.aspxhome.com/file/2023/8/131148_0s.png)
[译]Javascript风格要素(一)
2008-02-28 12:58:00
MySQL Order By语法
2011-01-04 19:58:00
ASP+FSO+框架实现ASP生成htm并分页的方法(批量)
2009-03-09 18:26:00
python对验证码降噪的实现示例代码
2021-01-02 09:54:17
![](https://img.aspxhome.com/file/2023/6/135296_0s.jpg)
miniconda3介绍、安装以及使用教程
2023-06-06 18:37:16
![](https://img.aspxhome.com/file/2023/6/127296_0s.jpg)
Python简单实现自动删除目录下空文件夹的方法
2021-07-28 20:28:39
Vue中keep-alive的两种应用方式
2024-05-09 15:10:53
![](https://img.aspxhome.com/file/2023/4/126604_0s.jpg)
python实现简单tftp(基于udp协议)
2021-01-30 15:01:23
![](https://img.aspxhome.com/file/2023/9/114599_0s.jpg)