Python按行读取文件的简单实现方法
1:readline()
file = open("sample.txt") while 1: line = file.readline() if not line: break pass # do something file.close()
一行一行得从文件读数据,显然比较慢;
不过很省内存;
测试读10M的sample.txt文件,每秒大约读32000行;
2:fileinput
import fileinput for line in fileinput.input("sample.txt"): pass
写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多;
3:readlines()
file = open("sample.txt") while 1: lines = file.readlines(100000) if not lines: break for line in lines: pass # do something file.close()
用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!
4:文件迭代器
每次只读取和显示一行,读取大文件时应该这样:
file = open("sample.txt") for line in file: pass # do something file.close()
相关推荐
hanxia 2020-06-01
idning 2020-02-14
蔷薇部落 2017-03-28
DreamPig 2019-06-27
一叶不知秋 2017-12-15
fuziwang 2017-06-30
Ninjajs 2017-06-06
CrazyDogWang 2016-11-08
wangpeng0 2018-06-22
小肖 2016-11-08
billbliss 2017-07-12
pythonpycharm 2017-07-11
pythonxuexi 2019-04-26
Triagen 2019-04-20
lispython 2019-04-20
hbupig 2014-02-13
pythonjw 2015-04-29
csssy00 2017-09-08
PythonGCS 2019-04-17