Python中以最快最少代码的读取文件内容方式

题目: 有一个jsonline格式的文件file.txt大小约为10K

普通方法1:

def get_lines():
	with open("file.txt", "rb") as f:
		return f.readlines()
	
if __name__ == '__main__':
	for e in get_lines():
		print(e)
"""
结果:
b'this is the first\n'
b'this is the second \n'
b'this is the third\n'
b'this is the four\n'

 
普通方法2:

for line in open("file.txt"):
	print(line, end=""
"""
结果为:
this is the first
this is the second 
this is the third
this is the four
"""

现在需要处理一个大小为10G文件,但是内存只有4G,如果在只修改get_lines 函数而其他代码保持不变的情况下,应该如何实现?需要考虑的问题都有那些?

# 除了使用f.readline()可以胜任,也可以借助线程来执行。
 def get_lines():
    for line in open("file.txt"):
    	print(type(line))
    	yield line # line相当于f.readline(), 为str类型


if __name__ == '__main__': 
	for i in get_lines():
    	print(i, end="")
"""
结果为:
<class 'str'>
this is the first
<class 'str'>
this is the second 
<class 'str'>
this is the third
<class 'str'>
this is the four 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值